简体   繁体   中英

Can't compile SFINAE in Visual Studio 10

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <functional>
#include <type_traits>

struct X {};
struct Y {};

__int8 f(X x) { return 0; }
__int16 f(...) { return 0; }

template <typename T> typename std::enable_if<sizeof(f(T())) == sizeof(__int8), int>::type call(T const& t) {
    std::cout << "In call with f available";
    f(t);
    return 0;
}

template <typename T> typename std::enable_if<sizeof(f(T())) == sizeof(__int16), int>::type call(T const& t) {
    std::cout << "In call without f available";
    return 0;
}

int main() {
    Y y; X x;
    call(y);
    call(x);
}

Seems to be a pretty simple use of SFINAE here, but the compiler throws an error, which is that it can't instantiate enable_if<false, int>::type . Any suggestions? Apparently this code compiles just fine on GCC (didn't ask which version).

Edit: This code compiles fine

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <functional>
#include <type_traits>

struct X {};
struct Y {};

__int8 f(X x) { return 0; }
__int16 f(...) { return 0; }

template<typename T> struct call_helper {
    static const int size = sizeof(f(T()));
};

template <typename T> typename std::enable_if<call_helper<T>::size == sizeof(__int8), int>::type call(T const& t) {
    std::cout << "In call with f available";
    f(t);
    return 0;
}

template <typename T> typename std::enable_if<call_helper<T>::size == sizeof(__int16), int>::type call(T const& t) {
    std::cout << "In call without f available";
    return 0;
}

int main() {
    Y y; X x;
    call(y);
    call(x);
}

So I'm perfectly happy to chalk this one up to being a bugarooney.

This compiles and works correctly in VS2010. Modified using suggestion by David.

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <functional>
#include <type_traits>

struct X {
  typedef X is_x;
  };
struct Y {};

__int8 f(X x) { return 0; }
__int16 f(...) { return 0; }

template < class T >
struct test {
  enum { result = sizeof(f(T())) };
  };

template <typename T>
typename std::enable_if< test<T>::result == sizeof(__int8), int>::type call(T const& t) {
    std::cout << "In call with f available" << std::endl;
    f(t);
    return 0;
}

template < typename T >
typename std::enable_if< test<T>::result == sizeof(__int16), int>::type call(T const& t) {
    std::cout << "In call without f available" << std::endl;
    return 0;
}

int main() {

    Y y; X x;
    call(y);
    call(x);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM