dimanche 16 décembre 2018

SFINAE not working to conditionally compile member function template

I'm trying you use std::enable_if to conditionally choose only one out of two member function template using SFINAE with this code:

#include <iostream>
#include <type_traits>

template<typename T>
struct C {
    template<typename Q = T, typename = typename std::enable_if<std::is_same<Q, int>::value>::type>
    int foo() {
        return 1;
    }

    template<typename Q = T, typename = typename std::enable_if<!std::is_same<Q, int>::value>::type>
    int foo() {
        return 0;
    }

};

int main() {
    std::cout << C<int>().foo() << std::endl;  //error member function foo already defined
}

but for some reason, visual c++ keeps giving me a compiler error that foo is already defined. Even though, it is clear that, depending on the class' template argument, only one function is well-formed. So SFINAE should remove the second one from consideration.

Any idea why this does not work?

Aucun commentaire:

Enregistrer un commentaire