本文介绍了通过参数启用时std :: enabled_if如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解enable_if的工作原理,并且我几乎了解了除

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\n";
}

如果enable_if中的表达式为true,则选择部分模板专用化,因此如果选择:

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

  1. 为什么在enable_if中只有条件而不指示第二个模板参数?
  2. 那么"type *"是什么类型?空白* ?如果是这样,为什么?
  3. 为什么是指针?

推荐答案

因为默认void就可以了.

是的,如果std::is_trivially_destructible<T>::value == true::type的类型将为void,这将导致::type*-> void*.

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

因此我们可以轻松地将其默认值设置为0.

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

我们使用std::enable_if的所有功能是检查某些属性(在这种情况下,检查T是否可微毁),如果这些结果导致false,则可以使用它创建格式错误的代码,并因此可以从重载解析中消除此功能.

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.

如果std::is_trivially_destructible<T>::value == false,则::type将不存在,因此代码格式错误.在SFINAE中,这很方便,因为随后将不考虑此重载以进行解决.

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.

这篇关于通过参数启用时std :: enabled_if如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 05:47