9he0nix
9he0nix

Reputation: 1

Wierd Initialization in Template Parameters

template <bool B, typename T = void> struct enable_if {using type = T;};
template <typename T> struct enable_if<false,T> {};

template<bool B, class T = void>
using enable_if_t = typename enable_if<B,T>::type;

template<
        typename T, 
        enable_if_t<is_integral<T>::value,bool> = true
        >
struct MyTypeWhichIsdependentOnIntegralTypes{};

The above code in C++ uses an enable_if, just wanted to know this weird syntax while using it enable_if_t<is_integral<T>::value,bool> = true why is = true necessary when I remove it and try to use the created type it gives error.

Upvotes: 0

Views: 68

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122458

Thats one application of SFINAE (substitution failure is not an error). When the condition in enable_if is true, you get

template<
        typename T, 
        bool = true
        >
struct MyTypeWhichIsdependentOnIntegralTypes{};

bool = true is an unnamed template argument with default value true. It serves little purpose when the condition is true. It is only there to fail when the condition is false:

template<
        typename T, 
        "not a type" = true   // <- enable_if<false,T> has no type member alias
        >
struct MyTypeWhichIsdependentOnIntegralTypes{};

The default argument is used so it isnt necessary to specify the argument:

MyTypeWhichIsdependentOnIntegralTypes<int> foo;
                                 //     ^^ no need to specify 2nd argument 
                                 //        because it has a default

Upvotes: 1

Related Questions