I don't undestand.
template<class T>
T foo2(T t, typename std::enable_if<std::is_integral<T>::value >::type* = nullptr)
{
return t;
}
type* = 0 ? What is this.
This is a way of achieving SFINAE : The function can only be selected if all the types can be substituted in properly.
If std::is_integral<T>::value
is false
(ie, T
is not an integral type), std::enable_if<...>
will have no member type
, thus a substitution failure happens and this function won't be called (and a different overload might).
If T
is an integral type, then typename std::enable_if<std::is_integral<T>::value >::type
will be void
, so the second parameter will be of type void*
. It is an unnamed parameter with default value nullptr
, so you don't have to specify it.
So you would call it like this:
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);
Note that this would normally be achieved either with a default template parameter:
// 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;
}
Or directly in the return type:
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;
}
And in C++20, you can use requires
(or the std::integral
concept in this case)
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;
}
In C/C++ you can, in a declaration of a function, omit the name of (a) parameter(s). This is a preferred style sometimes when separating an interface from an implementation to avoid having confusion between the names of the parameters of, say, a function prototype & an implementation. I have never quite seen someone do this before. But what they are then doing as @IgorTandetnik pointed out, is initialize that "dummy parameter" with a default value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.