[英]What is the meaning of “type* = nullptr”
我不明白。
template<class T>
T foo2(T t, typename std::enable_if<std::is_integral<T>::value >::type* = nullptr)
{
return t;
}
类型* = 0 ? 这是什么。
这是实现SFINAE的一种方式:只有在所有类型都可以正确替换的情况下,才能选择 function。
如果std::is_integral<T>::value
为false
(即T
不是整数类型), std::enable_if<...>
将没有成员type
,因此会发生替换失败并且此 function 不会被调用(并且可能会出现不同的重载)。
如果T
是整数类型,则typename std::enable_if<std::is_integral<T>::value >::type
将为void
,因此第二个参数将为void*
类型。 它是一个未命名的参数,默认值为nullptr
,因此您不必指定它。
所以你会这样称呼它:
foo2(0); // T is `int`, which is integral, so the function can be called
foo2(0, nullptr); // Same as above, but explicitly passing the parameter
// Can't call the function, because `double` is not integral,
// so second type is a substitution failure
// foo2(0.0);
请注意,这通常可以使用默认模板参数来实现:
// Same `void*` if integral, else substitution failure
template<class T, typename std::enable_if<std::is_integral<T>::value >::type* = nullptr>
T foo2(T t)
{
return t;
}
// Or alternatively with an `int` if integral, else substitution failure
template<class T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
T foo2(T t)
{
return t;
}
或者直接在返回类型中:
template<class T>
// Returns `T` if it's integral, else substitution failure
typename std::enable_if<std::is_integral<T>::value, T>::type foo2(T t)
{
return t;
}
在 C++20 中,您可以使用requires
(或在这种情况下使用std::integral
概念)
template<class T> requires std::is_integral_v<T>
T foo2(T t)
{
return t;
}
template<std::integral T>
T foo2(T t)
{
return t;
}
在 C/C++ 中,您可以在 function 的声明中省略 (a) 参数的名称。 有时,在将接口与实现分开时,这是一种首选样式,以避免混淆参数名称,例如 function 原型和实现。 我以前从未见过有人这样做。 但是正如@IgorTandetnik 指出的那样,他们正在做的是用默认值初始化那个“虚拟参数”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.