c++ - 检测类是否具有重载函数在 Comeau 编译器上失败

标签 c++ templates overloading sfinae comeau

我正在尝试使用 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 进行任何修改以解决该问题?

最佳答案

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

关于c++ - 检测类是否具有重载函数在 Comeau 编译器上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2768508/

相关文章:

c# - 尝试调用有效方法重载时出现奇怪的 "assembly not referenced"错误

c++ - Boost库,如何获取相邻节点?

c++ - Qt 4.8 : Text on QPushButton becomes selected when window is shown

c++ - 如何使用grabWindow只对窗口的某个区域进行截图?

c++ - 从基类类型的指针数组调用派生类的方法。 (C++)

c++ - 通过初始化列表中的模板类构造函数调用非模板基类的构造函数

C++ 模板和访问命名空间

java - 这个函数是调用自身还是调用重载?

python - 将 Django 指向不同的模板目录

c++ - 如何在 C++ 中消除可变参数函数与另一个函数的歧义