[英]Can I use enable_if together with typedef?
我想定义一个类型取决于某些条件的变量。 我想要这样的东西:
typedef typename enable_if<cond, int>::type Type;
typedef typename enable_if<!cond, double>::type Type;
但是编译器说我重新定义了类型。
我怎样才能做到这一点?
我可以将
enable_if
与typedef一起使用吗?
不,你不能。 如果条件为假,则std::enable_if
将类型std::enable_if
为undefined。 仅当条件为true时,才定义成员type
。
template< bool B, class T = void > struct enable_if;
如果
B
为true
,则std::enable_if
具有公共成员typedef类型,等于T
; 否则,没有成员typedef。
为了使typedef正常工作,当条件为true和false时,这两种情况都需要一个类型。 enable_if
的实现是为了协助与SFINAE相关的场景。
所以呢
我怎样才能做到这一点?
使用std::conditional
。 条件的条件true
与false
都将包含一个成员typedef( type
)。
template< bool B, class T, class F > struct conditional;
提供构件的typedef类型,其被定义为
T
如果B
是true
在编译时,或作为F
如果B
是false
。
因此,以下内容就足够了;
typedef typename std::conditional<cond, int, double>::type Type;
或更简洁;
using Type = std::conditional_t<cond, int, double>;
您需要使用std::conditional
:
#include <type_traits>
// c++11:
typedef typename std::conditional<cond, int, double>::type Type;
// c++14:
typedef std::conditional_t<cond, int, double> Type;
另请注意,自c ++ 11起,您可以将using
关键字用于类型和模板别名(我认为这样更简洁):
// c++11
using Type = typename std::conditional<cond, int, double>::type;
// c++14
using Type = std::conditional_t<cond, int, double>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.