Jom*_*oma 2 c++ visual-c++ c++11
我不明白。
template<class T>
T foo2(T t, typename std::enable_if<std::is_integral<T>::value >::type* = nullptr)
{
return t;
}
Run Code Online (Sandbox Code Playgroud)
类型* = 0 ? 这是什么。
这是实现SFINAE的一种方法:只有所有类型都可以正确替换时才能选择该功能。
如果std::is_integral<T>::value是false(即T不是整型),std::enable_if<...>则将没有 member 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);
Run Code Online (Sandbox Code Playgroud)
请注意,这通常可以通过默认模板参数来实现:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
或者直接在返回类型中:
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;
}
Run Code Online (Sandbox Code Playgroud)
在 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
622 次 |
| 最近记录: |