I am trying to use SFINAE to determine if a class has an overloaded member function that takes on a particular type. The code that I seem to work correctly in Visual Studio and GCC, but does not compile using the Comeau compiler.
Here is the code I'm using:
#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 ) }
Error message: not a single instance of the CallFunc function template matches the argument list. HasFunc :: Has seems to be false for int and float when this should be true.
Is this a bug in the Comeau compiler? Am I doing something non-standard? And if so, what do I need to do to fix this?
Update
I think the question now becomes, if this is a mistake, is there anything I can do to get around this? I tried using static_cast on & TestClass :: Func, but this is not possible, or I did not get the syntax correctly because I could not compile it.
If this is not a solution, are there any changes I can make to TestClass or HasFunc to get around the problem?
c ++ overloading templates sfinae
Frank
source share