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

时间:2016-08-22 13:28:19

标签: c++ templates inheritance derived-class

给定是具有一个模板参数

的类MyClass
template<typename T>
class MyClass
{
    //...
};

和另一个包含两个模板参数的类MySecondClass

template<typename T, typename U>
class MySecondClass
{
    //...
};

我想要做的是将MyClass限制为只允许T MySecondClass的派生类型。我已经知道我需要像

这样的东西
template<typename T, typename = std::enable_if<std::is_base_of<MySecondClass<?,?>, T>::value>>
class MyClass
{
    //...
}

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

2 个答案:

答案 0 :(得分:7)

您可以为基本模板使用模板模板参数,然后检查@model App.Models.MyItem @Html.DropDownListFor(m => m.ID, new SelectList(ViewBag.MyItems, "Value", "Text")) @Html.DropDownListFor(m => m.Forign_element_id, new SelectList(ViewBag.MyItems, "Value", "Text")) 是否可以转换为某些T*

Temp<Args...>

Live Demo

答案 1 :(得分:3)

您可以使用自定义特征来检查类型是否来自模板。然后在static_assert

中使用此特征
#include <type_traits>

template <template <typename...> class T, typename U>
struct is_derived_from_template
{
private:
    template <typename... Args>
    static decltype(static_cast<const T<Args...>&>(std::declval<U>()), std::true_type{}) test(
            const T<Args...>&);
    static std::false_type test(...);

public:
    static constexpr bool value = decltype(test(std::declval<U>()))::value;
};


template <typename T1, typename T2>
struct MyParentClass
{
};

template<typename T>
struct MyClass
{
    static_assert(is_derived_from_template<MyParentClass, T>::value, "T must derive from MyParentClass");
};


struct DerivedFromMyParentClass : MyParentClass<int, float>{};

struct Foo{};

int main()
{
    MyClass<DerivedFromMyParentClass> m;
    MyClass<Foo> f;
}

live example