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