Cannot get SFINAE to work
Asked Answered
N

1

5

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?

Nicobarese answered 10/12, 2015 at 15:23 Comment(5)
You need to write typename std::enable_if<...>::type because type is dependent. Read this. If you can use C++14 you can use std::enable_if_t<...> instead and you won't have this problem.Palmy
the best would be to place enable_ifs in template parameters to not clutter function argumentsDisjoined
I made an edit to your code. I presume these were things that you just omitted or typed incorrectly, but I added them for clarity.Eskridge
Further, is there any reason you didn't use is_void and is_integral? Based on your username, I assume these are just learning exercises. :)Eskridge
@Eskridge Based on my user name, I did not use them because I haven't learnt them yet :-) Thank you for mentioning them.Nicobarese
O
7

You need a couple of typenames for this to work:

// For classes that declare T = int
template <class C>
void f(C &c,
       typename 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,
       typename std::enable_if<std::is_same<typename C::T, void>::value, int>::type = 0) {
    std::cout << "Without T" << std::endl;
}

Or if your compiler supports C++14 you can use std::enable_if_t:

// For classes that declare T = int
template <class C>
void f(C &c,
       std::enable_if_t<!std::is_same<typename C::T, void>::value, int> = 0) {
    std::cout << "With T" << std::endl;
}

// For classes that declare T = void
template <class C>
void f(C &c,
       std::enable_if_t<std::is_same<typename C::T, void>::value, int> = 0) {
    std::cout << "Without T" << std::endl;
}
Offshoot answered 10/12, 2015 at 15:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.