I've been trying to use the sfinae principle in some code and have been
getting many compiler errors. So I decided to try a very simplified
version to see if I had the idea correct. Here's the example:
#include <iostream>
template <typename T>
class IsClassT
{
private:
typedef char One;
typedef struct { char a[2]; } Two;
template <typename C> static One test(int C::*);
template <typename C> static Two test(...);
public:
enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 };
enum { No = !Yes };
};
class A
{
public:
int a;
};
int main()
{
using namespace std;
if(IsClassT<A>::Yes)
cout << "A is a class!" << endl;
if(IsClassT<A*>::Yes)
cout << "A* is a class too!" << endl;
return 0;
}
This you may recognize is copied DIRECTLY from "C++ Templates" by
Josuttis, at least the template part anyway.
This is supposed to work right? Why does it think it can't find the
"test" function? It looks like the compiler isn't matching either of
those overloads. Also, as neither of those "test" functions are
actually being called (sizeof doesn't actually call the function), code
doesn't need to be provided for them.
Please, any help would be GREATLY appreciated!! Posted below are the
error messages I got when compiling with g++ 3.2.2 and 3.4.2.
With g++ 3.2.2
sfinae.cxx:5: warning: all member functions in class `IsClassT<T>' are
private
sfinae.cxx: In instantiation of `IsClassT<A>':
sfinae.cxx:26: instantiated from here
sfinae.cxx:26: no method `IsClassT<A>::test<A>'
sfinae.cxx:26: enumerator value for `Yes' not integer constant
sfinae.cxx: In instantiation of `IsClassT<A*>':
sfinae.cxx:28: instantiated from here
sfinae.cxx:28: no method `IsClassT<A*>::test<A*>'
sfinae.cxx:28: enumerator value for `Yes' not integer constant
With g++ 3.4.2:
sfinae.cxx:12: error: expected primary-expression before '>' token
sfinae.cxx: In instantiation of `IsClassT<A>':
sfinae.cxx:26: instantiated from here
sfinae.cxx:12: error: enumerator value for `Yes' not integer constant
sfinae.cxx: In instantiation of `IsClassT<A*>':
sfinae.cxx:28: instantiated from here
sfinae.cxx:12: error: enumerator value for `Yes' not integer constant