有没有办法使用 SFINAE 来检测给定类的自由函数是否重载?
基本上,我有以下解决方案:
struct has_no_f { };
struct has_f { };
void f(has_f const& x) { }
template <typename T>
enable_if<has_function<T, f>::value, int>::type call(T const&) {
std::cout << "has f" << std::endl;
}
template <typename T>
disable_if<has_function<T, f>::value, int>::type call(T const&) {
std::cout << "has no f" << std::endl;
}
int main() {
call(has_no_f()); // "has no f"
call(has_f()); // "has f"
}
简直超载call
不起作用,因为实际上有很多foo
and bar
类型和call
函数不知道它们(基本上call
位于 a 内部,用户提供自己的类型)。
我无法使用 C++0x,并且我需要一个适用于所有现代编译器的工作解决方案。
注:a的解决方案类似的问题 https://stackoverflow.com/q/3375652/1968不幸的是在这里不起作用。
#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);
}
对 f() 返回类型的快速修改产生了传统的 SFINAE 解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)