c++ - 通过参数启用时 std::enabled_if 如何工作

标签 c++ templates metaprogramming enable-if

我正在尝试了解 enable_if 的工作原理,并且我了解几乎所有内容,除了来自

的场景 #3

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 中的表达式为真,则选择部分模板特化,因此如果选择:

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

最佳答案

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

因为默认void就好了。

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

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

Why is it pointer ?

所以我们可以很容易地给它一个默认值 0 .


所有我们使用的 std::enable_if for 是检查某些属性(在这种情况下检查 T 是否可以轻易破坏),如果这些导致 false然后我们用它来创建格式错误的代码,从而从重载决策中消除这个函数。

如果std::is_trivially_destructible<T>::value == false然后 ::type将不存在,因此代码将是错误的。在 SFINAE 中,这很方便,因为此过载将不会被考虑用于解决。

关于c++ - 通过参数启用时 std::enabled_if 如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51785354/

相关文章:

c++ - 如何判断模板类型是基本类型还是类

c++ - 访问 getter 的真正底层类型?

c++ - 在模板类中时枚举中的整数溢出

c++ - OpenGL 退化 GL_TRIANGLES 共享相同的顶点

c++ - 使用 pimpl 习惯用法时如何创建私有(private)静态常量字符串

c++ - 将 string& 的值设置为 string

c++ - 将 std::set 与自定义比较器进行比较

c++ - 将函数查找与 C++ 中的模板混淆

java - 是否已更新 JavaBean 规范以反射(reflect)注解的存在

c++ - 指向常量指针的重复符号错误,但 C++ 中的常量指针不存在