This is my first attempt at SFINAE:
#include <type_traits>
#include <iostream>
struct C1 {
using T = int;
};
struct C2 {
using T = void;
};
// For classes that declare T = int
template <class C>
void f(C &c,
std::enable_if<!std::is_same<typename C::T, void>::value, int>::type = 0) {
std::cout << "With T" << std::endl;
}
// For classes that declare T = void
template <class C>
void f(C &c,
std::enable_if<std::is_same<typename C::T, void>::value, int>::type = 0) {
std::cout << "Without T" << std::endl;
}
int main() {
C1 c1;
f(c1); // With T
C2 c2;
f(c2); // Without T
return 0;
}
The compiler (gcc 4.8.2) complains:
‘std::enable_if<!(std::is_same<typename C::T, void>::value), int>::type’ is not a type
What am I doing wrong?
typename std::enable_if<...>::type
becausetype
is dependent. Read this. If you can use C++14 you can usestd::enable_if_t<...>
instead and you won't have this problem. – Palmyenable_if
s in template parameters to not clutter function arguments – Disjoinedis_void
andis_integral
? Based on your username, I assume these are just learning exercises. :) – Eskridge