"type* = nullptr"的含义是什么

What is the meaning of "type* = nullptr"

本文关键字:是什么 nullptr type      更新时间:2023-10-16

我不站立。

template<class T>
T foo2(T t, typename std::enable_if<std::is_integral<T>::value >::type* = nullptr) 
{
return t;
}

类型* = 0?这是怎麽。

这是实现SFINAE的一种方法:只有在所有类型都可以正确替换的情况下,才能选择该函数。

如果std::is_integral<T>::valuefalse的(即,T不是整型(,std::enable_if<...>将没有成员type,因此会发生替换失败,并且不会调用此函数(并且可能会调用不同的重载(。

如果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++ 中,您可以在函数的声明中省略 (a( 参数的名称。有时,当将接口与实现分开时,这是一种首选样式,以避免混淆参数名称,例如,函数原型和实现。我以前从未见过有人这样做。但是,正如@IgorTandetnik指出的那样,他们正在做的是使用默认值初始化该"虚拟参数"。