Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

c++ - How does std::enabled_if work when enabling via a parameter

I'm trying to understand how enable_if works and I understand almost everything except scenario #3 from

https://en.cppreference.com/w/cpp/types/enable_if

template<class T>
void destroy(T* t, 
         typename 
std::enable_if<std::is_trivially_destructible<T>::value>::type* = 0) 
{
    std::cout << "destroying trivially destructible T
";
}

if the expression in enable_if is true then partial template specialization is chosen, so if it is chosen:

  1. why in enable_if is only condition without indicating second template parameter ?
  2. What type is "type*" then ? void* ? if so, why ?
  3. Why is it pointer ?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

why in enable_if is only condition without indicating second template parameter ?

Because the default void is just fine.

What type is "type*" then ? void* ? if so, why ?

Yes, ::type will be of type void if std::is_trivially_destructible<T>::value == true, this will result in ::type* -> void*.

Why is it pointer ?

So we can easily give it a default value of 0.


All we're using std::enable_if for is to check for certain attributes (in this case checking if T is trivially destructible), if these result in false then we use it to create ill-formed code and thus eliminate this function from overload resolution.

If std::is_trivially_destructible<T>::value == false then ::type will not exist and thus the code will be ill-formed. In SFINAE this is handy since this overload will then not be considered for resolution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...