简体   繁体   中英

What's the meaning of std::enable_if_t = 0

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM