Is it possible to use enable_if together with typedef?

I want to define a variable for which the type depends on some condition. I want something like this:

typedef typename enable_if<cond, int>::type Type;
typedef typename enable_if<!cond, double>::type Type;

But the coniler says that I redefined the type.

How can i do this?

+4
source share
2 answers

Can I use it enable_ifwith typedef?

No, you can’t. std::enable_ifleaves the type undefined if the condition is false. Only if the condition is true is a member defined type;

template< bool B, class T = void >
 struct enable_if;

If B- true, std::enable_ifhas the type publicped typedef equal to T; otherwise there is no typedef member.

typedef , . enable_if , SFINAE.

,

?

std::conditional. typedef (type) true false .

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>;
+9

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;

, ++ 11 using ( , ):

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

// c++14
using Type = std::conditional_t<cond, int, double>;
+7

Source: https://habr.com/ru/post/1648208/


All Articles