9

渡されたテンプレートパラメータがFooの子であるという制限を適用したいとします。

タイプ特性を介してこれを実施する方法はありますか?コンパイル時のstatic_assert失敗は素晴らしいでしょう。

以下のコードでは、2つの部分からなる(個別の)質問にしましょう。

  1. My_Limited_Template<Bar>コンパイルのみを許可します。
  2. My_Limited_Template<TBar>コンパイルのみを許可します。

編集 私は悪い命名をお詫びします:TBarそしてTBaz意図的に非テンプレートクラスであることを意味します。パート1のクラスから明確にするために、名前の前にTを付けました。

コード

struct Foo { };                // no
struct Bar : public Foo { };   // yes
struct Baz { };                // no

template< typename T >
struct TFoo { };                       // no
struct TBar : public TFoo<TBar> { };   // yes
struct TBaz { };                       // no

template< typename T >
struct My_Limited_Template
{
  // Part One:
  //   My_Limited_Template<Foo>  // disallow
  //   My_Limited_Template<Bar>  // allow
  //   My_Limited_Template<Baz>  // disallow
  // 
  // Part Two:
  //   My_Limited_Template<TFoo<int>> // disallow
  //   My_Limited_Template<TBar>      // allow
  //   My_Limited_Template<TBaz>      // disallow
};
4

1 に答える 1

1

TBarとの定義に誤りがあったと思いますが、TBas私の変更が正しいことを確認してください。

#include <type_traits>    

struct Foo { };                // don't allow this
struct Bar : public Foo { };   // allow this
struct Baz { };                // don't allow this

template< typename T > struct TFoo { };                       
template< typename T > struct TBar : public TFoo<TBar<T>> { }; 
template< typename T > struct TBaz { };                       

template< typename T >
struct My_Limited_Template
{
        static_assert(
                (std::is_base_of<Foo,T>::value && !std::is_same<T,Foo>::value)
                || 
                (std::is_base_of<TFoo<T>,T>::value && !std::is_same<T,TFoo<T>>::value),
                "fail2"
        ); 
};
于 2012-12-25T07:17:53.257 に答える