我可以将enable_if与typedef一起使用吗?

map*_*ple 7 c++ templates typedef redefine enable-if

我想定义一个类型取决于某些条件的变量.我想要这样的东西:

typedef typename enable_if<cond, int>::type Type;
typedef typename enable_if<!cond, double>::type Type;
Run Code Online (Sandbox Code Playgroud)

但是这个conpiler说我重新定义了这种类型.

我怎样才能做到这一点?

Nia*_*all 11

我可以enable_if和typedef一起使用吗?

不,你不能.std::enable_if如果条件为false,则将类型保留为undefined.只有条件为真,才type定义成员;

template< bool B, class T = void >
 struct enable_if;
Run Code Online (Sandbox Code Playgroud)

如果Btrue,std::enable_if有一个公共成员typedef类型,等于T; 否则,没有成员typedef.

为了使typedef正常工作,当条件为真且为假时,它需要两种情况的类型.enable_if实施以协助与S​​FINAE相关的情景.

那么

我怎样才能做到这一点?

使用std::conditional.条件将包含条件type的结果truefalse结果的成员typedef().

template< bool B, class T, class F >
 struct conditional;
Run Code Online (Sandbox Code Playgroud)

提供构件的typedef类型,它被定义为T如果Btrue在编译时,或作为F如果Bfalse.

因此,以下就足够了;

typedef typename std::conditional<cond, int, double>::type Type;
Run Code Online (Sandbox Code Playgroud)

或者更简洁;

using Type = std::conditional_t<cond, int, double>;
Run Code Online (Sandbox Code Playgroud)


Hol*_*olt 8

你需要使用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;
Run Code Online (Sandbox Code Playgroud)

另请注意,从c ++ 11开始,您可以使用using关键字作为类型和模板别名(在我看来有点清晰):

// c++11
using Type = typename std::conditional<cond, int, double>::type;

// c++14
using Type = std::conditional_t<cond, int, double>;
Run Code Online (Sandbox Code Playgroud)