6

有没有办法使用 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是行不通的,因为实际上有很多foobar类型,并且call函数不知道它们(基本上call在 a 内部,用户提供自己的类型)。

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

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

4

2 回答 2

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

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

于 2011-01-26T15:17:24.537 回答
3

如果boost允许,以下代码可能符合您的目的:

#include <boost/type_traits.hpp>
#include <boost/utility/enable_if.hpp>
using namespace boost;

// user code
struct A {};
static void f( A const& ) {}
struct B {};


// code for has_f
static void f(...); // this function has to be a free standing one

template< class T >
struct has_f {
  template< class U >
  static char deduce( U(&)( T const& ) );

  template< class U, class V >
  static typename disable_if_c< is_same< V, T >::value, char(&)[2] >::type
  deduce( U(&)( V const& ) );

  static char (&deduce( ... ))[2];

  static bool const value = (1 == sizeof deduce( f ));
};

int main()
{
  cout<< has_f<A>::value <<endl;
  cout<< has_f<B>::value <<endl;
}

但是,有严格的限制。
该代码假定所有用户函数都有签名( T const& ),因此( T )是不允许的。
上面的函数void f(...)似乎需要是一个独立的函数。
如果编译器按预期正常执行两阶段查找,则可能所有用户函数都必须出现在has_f类模板的定义之前。
老实说,我对代码的有用性没有信心,但无论如何我希望这会有所帮助。

于 2011-01-26T19:15:17.837 回答