类的类型模板参数的限制范围 [英] Limit range of type template arguments for class
本文介绍了类的类型模板参数的限制范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在没有任意typedef的情况下如何实现这种效果?
How can I have this effect without the arbitrary typedefs?
#include <type_traits>
#include <iostream>
typedef int Primary;
typedef float Secondary;
template<Class C, std::enable_if<std::is_same<Class, Primary>::value || std::is_same<Class, Secondary>::value> = 0>
class Entity {
public:
template<std::enable_if<std::is_same<Class, Secondary>::value>::type = 0>
void onlyLegalForSecondaryEntities() {
std::cout << "Works" << std::endl;
}
};
int main() {
Entity<Secondary> e;
e.onlyLegalForSecondaryEntities();
return 0;
}
是否有更优雅的方式来生成此内容,从而使实体
只能使用 Primary
或 Secondary
作为模板参数来实例化吗?
Is there a more elegant way to produce this so that Entity
can only be instantiated with Primary
or Secondary
as template arguments?
推荐答案
更正代码中的错误后:
在C ++ 1z中您可以使用 std :: disjunction
:
In C++1z you can easily roll a trait is_any
with std::disjunction
:
template<typename T, typename... Others>
struct is_any : std::disjunction<std::is_same<T, Others>...>
{
};
在C ++ 11中,您可以实现分离
as
In C++11, you can implement disjuncation
as
template<class...> struct disjunction : std::false_type { };
template<class B1> struct disjunction<B1> : B1 { };
template<class B1, class... Bn>
struct disjunction<B1, Bn...>
: std::conditional<B1::value != false, B1, disjunction<Bn...>>::type { };
然后将您的班级模板定义为
Then define your class template as
template<class C, typename std::enable_if<is_any<C, Primary, Secondary>::value>::type* = nullptr>
class Entity {
public:
template<typename std::enable_if<std::is_same<C, Secondary>::value>::type* = nullptr>
void onlyLegalForSecondaryEntities() {
std::cout << "Works" << std::endl;
}
};
您可以更进一步,并创建 enable_if_any
别名以解决到 void
(如果可能):
You can take this further and make enable_if_any
alias that would resolve to void
if possible:
template<typename This, typename... Elems>
using enable_if_is_any = typename std::enable_if<is_any<This, Elems...>::value>::type;
template<class C, enable_if_is_any<C, Primary, Secondary>* = nullptr>
class Entity {
public:
template<typename std::enable_if<std::is_same<C, Secondary>::value>::type* = nullptr>
void onlyLegalForSecondaryEntities() {
std::cout << "Works" << std::endl;
}
};
这篇关于类的类型模板参数的限制范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文