What's the meaning of std::enable_if_t = 0
Asked Answered
R

1

7

I was reading std::enable_if, and noticed the following.

template <typename Integer,
          std::enable_if_t<std::is_integral<Integer>::value, int> = 0
>
T(Integer) : m_type(int_t) {}

Since std::enable_if_t is a type, and it can be evaluated to int or void for this case, so the above code can be evaluated to

template <typename Integer,
          int = 0
>
T(Integer) : m_type(int_t) {}

or

template <typename Integer,
          void = 0
>
T(Integer) : m_type(int_t) {}

I can't understand int = 0 or void = 0, would someone help me with this? Thanks.

Rosena answered 4/3, 2020 at 14:21 Comment(0)
C
14

Since std::enable_if_t is a type, and it can be evaluated to int or void for this case, so the above code can be evaluated to ...

This is not correct. With std::enable_if_t<std::is_integral<Integer>::value, int> the only type std::enable_if_t can be is int. If std::is_integral<Integer>::value is not true, then there is no member at all and the template instantiation is thrown out. That means it only resolves to

template <typename Integer,
          int = 0
>
T(Integer) : m_type(int_t) {}

where int = 0 is just an unnamed non-type template parameter with the value of 0.

The reason we do = 0 is so that it has a default value and we don't need to pass a value to it when declaring a object of this type. Without it you would not be able to use this constructor at all as there is no way to specify the template parameters of a constructor. Even if this wasn't a constructor, you would still want to use a default value so the user does not need to pass a unneeded value to that unnamed and unused template parmater.

Cureton answered 4/3, 2020 at 14:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.