Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I 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 conpiler says I redefined the type.

How can I do this?

like image 556
maple Avatar asked Jul 18 '16 07:07

maple


2 Answers

Can I use enable_if together with typedef?

No you can't. std::enable_if leaves the type undefined if the condition is false. Only if the condition is true, is the member type is defined;

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

If B is true, std::enable_if has a public member typedef type, equal to T; otherwise, there is no member typedef.

For the typedef to work correctly, it needs a type for both cases, when the condition is true and when it is false. enable_if is implemented to assist in scenarios related to SFINAE.

So then

How can I do this?

Use std::conditional. Conditional will contain a member typedef (type) for both the true and false result of the condition.

template< bool B, class T, class F >
 struct conditional;

Provides member typedef type, which is defined as T if B is true at compile time, or as F if B is false.

Hence, the following would suffice;

typedef typename std::conditional<cond, int, double>::type Type;

Or the more terse;

using Type = std::conditional_t<cond, int, double>;
like image 100
Niall Avatar answered Sep 25 '22 02:09

Niall


You need to use 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;

Also note that since c++11 you can use the using keyword for type and template aliases (a bit cleaner in my opinion):

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

// c++14
using Type = std::conditional_t<cond, int, double>;
like image 41
Holt Avatar answered Sep 25 '22 02:09

Holt