C++类模板参数必须具有特定的父类

use*_*903 8 c++ inheritance templates derived-class

给定是一个MyClass具有一个模板参数的类

template<typename T>
class MyClass
{
    //...
};
Run Code Online (Sandbox Code Playgroud)

和另一个MySecondClass有两个模板参数的类.

template<typename T, typename U>
class MySecondClass
{
    //...
};
Run Code Online (Sandbox Code Playgroud)

我想要做的是限制MyClass只允许T一个派生类型MySecondClass.我已经知道我需要类似的东西

template<typename T, typename = std::enable_if<std::is_base_of<MySecondClass<?,?>, T>::value>>
class MyClass
{
    //...
}
Run Code Online (Sandbox Code Playgroud)

我只是不确定要放什么,?因为我想允许所有可能MySecondClass的.

Tar*_*ama 7

您可以使用模板模板参数作为基本模板,然后检查是否T*可以将其转换为某些模板Temp<Args...>:

template <template <typename...> class Of, typename T>
struct is_base_instantiation_of {
    template <typename... Args>
    static std::true_type test (Of<Args...>*);
    static std::false_type test (...);

    using type = decltype(test(std::declval<T*>()));
    static constexpr auto value = type::value;
};
Run Code Online (Sandbox Code Playgroud)

现场演示

  • @Cornstalks我认为这是因为`int`不是从`MyParentClass`模板类派生的(因此`enable_if_t`失败并确保`MyClass`不是`MyClass <int>`的重载解析的一部分). (3认同)