SFINAE:检测类是否具有自由功能

Kon*_*lph 6 c++ templates sfinae

有没有办法,使用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"
}
Run Code Online (Sandbox Code Playgroud)

简单地重载call不起作用,因为实际上有很多foobar类型,并且call函数不知道它们(基本上call是在一个内部,用户提供它们自己的类型).

我不能使用C++ 0x,我需要一个适用于所有现代编译器的工作解决方案.

注意:遗憾的是,类似问题的解决方案在这里不起作用.

Pup*_*ppy 3

#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);
}
Run Code Online (Sandbox Code Playgroud)

对 f() 返回类型的快速修改产生了传统的 SFINAE 解决方案。