6

我正在尝试使用 SFINAE 来检测一个类是否具有采用某种类型的重载成员函数。我的代码在 Visual Studio 和 GCC 中似乎可以正常工作,但不能使用 Comeau 在线编译器进行编译。

这是我正在使用的代码:

#include <stdio.h>

//Comeau doesnt' have boost, so define our own enable_if_c
template<bool value> struct enable_if_c { typedef void type; };
template<> struct enable_if_c< false > {}; 


//Class that has the overloaded member function
class TestClass
{
public:
    void Func(float value) { printf( "%f\n", value ); }
    void Func(int value) { printf( "%i\n", value ); }
};


//Struct to detect if TestClass has an overloaded member function for type T
template<typename T>
struct HasFunc
{
    template<typename U, void (TestClass::*)( U )> struct SFINAE {};
    template<typename U> static char Test(SFINAE<U, &TestClass::Func>*);
    template<typename U> static int Test(...);
    static const bool Has = sizeof(Test<T>(0)) == sizeof(char);
};


//Use enable_if_c to only allow the function call if TestClass has a valid overload for T
template<typename T> typename enable_if_c<HasFunc<T>::Has>::type CallFunc(TestClass &test, T value) { test.Func( value ); } 

int main()
{
    float value1 = 0.0f;
    int value2 = 0;
    TestClass testClass;
    CallFunc( testClass, value1 );  //Should call TestClass::Func( float )
    CallFunc( testClass, value2 );  //Should call TestClass::Func( int )
}

错误消息是:没有函数模板“CallFunc”的实例与参数列表匹配。似乎 HasFunc::Has 对 int 为假,而当它应该为真时为 float。

这是 Comeau 编译器中的错误吗?我在做一些不标准的事情吗?如果是这样,我需要做什么来修复它?

更新

我想现在的问题变成了,如果这是一个错误,我能做些什么来解决它吗?我尝试在 &TestClass::Func 上使用 static_cast,但要么这是不可能的,要么我没有得到正确的语法,因为我无法编译它。

如果这不是解决方案,我是否可以对 TestClass 或 HasFunc 进行任何修改以解决该问题?

4

1 回答 1

0

我怀疑问题是因为 TestClass 重载了 Func 并且 Comeau 编译器无法消除 &TestClass::Func 的歧义,即使它应该。

于 2010-05-04T20:01:40.903 回答