SFINAE:检测类是否具有自由功能 [英] SFINAE: detect if class has free function
问题描述
有没有一种使用SFINAE的方法来检测给定类的自由函数是否被重载了?
Is there a way, using SFINAE, to detect whether a free function is overloaded for a given class?
基本上,我有以下解决方案:
Basically, I’ve got the following solution:
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
和 bar
类型以及 call
函数对此一无所知(基本上 call
位于a内,用户提供自己的类型).
Simply overloading call
doesn’t work since there are actually a lot of foo
and bar
types and the call
function has no knowledge of them (basically call
is inside a and the users supply their own types).
我无法使用C ++ 0x,并且需要适用于所有现代编译器的解决方案.
I cannot use C++0x, and I need a working solution for all modern compilers.
注意:类似问题的解决方案不幸的是在这里不起作用.
Note: the solution to a similar question unfortunately doesn’t work here.
推荐答案
#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解决方案.
A quick modification of the return types of f() yields the traditional SFINAE solution.
这篇关于SFINAE:检测类是否具有自由功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!