gpt4 book ai didi

c++ - 无法在 Visual Studio 10 中编译 SFINAE

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:13:14 26 4
gpt4 key购买 nike

#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);
}

这里好像是很简单的SFINAE的使用,但是编译器报错,就是不能实例化enable_if<false, int>::type .有什么建议么?显然这段代码在 GCC 上编译得很好(没有问哪个版本)。

编辑:这段代码编译正常

#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);
}

因此,我非常乐意将此归结为故障。

最佳答案

这在 VS2010 中编译和工作正常。使用 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);
}

关于c++ - 无法在 Visual Studio 10 中编译 SFINAE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4806238/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com