给定是具有一个模板参数
的类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
。
答案 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...>
答案 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;
}