Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between following code, why one works and the other doesn't?

i wanna define a function whose behavior depends on whether its parameter is pod type, i do this in two ways:

first

template <typename T, typename = typename std::enable_if<std::is_pod<T>::value>::type>
void f(const T&) {
    //...
}
template <typename T, typename = typename std::enable_if<!std::is_pod<T>::value>::type>>
void f(const T&) {
    //...
}

second

template <typename T>
typename std::enable_if<std::is_pod<T>::value>::type f(const T&) {
    //...
}
template <typename T>
typename std::enable_if<!std::is_pod<T>::value>::type f(const T&) {
    //...
}

the second works well while the first is error. compiler complains redefine f in the first case. I wanna know the difference between them. and why the first is error.

thanks for reading, please help me!.

like image 832
Sherwin Avatar asked Mar 14 '23 14:03

Sherwin


1 Answers

Default arguments on a template parameter list are not part of a function signature, thus, the two overloads have equal signatures from the compiler's perspective. Instead, you can make the result of std::enable_if a template parameter itself:

template <typename T, typename std::enable_if<std::is_pod<T>::value, int>::type = 0>
void f(const T&) {}

template <typename T, typename std::enable_if<!std::is_pod<T>::value, int>::type = 0>
void f(const T&) {}
like image 83
Piotr Skotnicki Avatar answered Apr 29 '23 17:04

Piotr Skotnicki