如何对模板参数强制实施子X限制?

kfm*_*e04 9 c++ templates type-traits c++11

假设我想强制传入的模板参数是Foo的子级的限制.

有没有办法通过类型特征来强制执行此操作?编译时static_assert失败会很棒.

在下面的代码中,让我们把它作为一个由两部分组成的(单独的)问题.

  1. 仅允许My_Limited_Template<Bar>编译.
  2. 仅允许My_Limited_Template<TBar>编译.

编辑 我为错误的命名道歉:TBar并且TBaz意图是非模板类用于目的.我只是在名称前附加了T,以消除第1部分中的类的歧义.

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
};
Run Code Online (Sandbox Code Playgroud)

Leo*_*sky 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"
        ); 
};
Run Code Online (Sandbox Code Playgroud)