我正在尝试了解 enable_if 的工作原理,并且我了解几乎所有内容,除了来自
的场景 #3https://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 中的表达式为真,则选择部分模板特化,因此如果选择:
- 为什么在 enable_if 中只是条件而不指示第二个模板参数?
- 那么“type*”是什么类型?空白* ?如果是,为什么?
- 为什么是指针?
最佳答案
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/