Ask for help about type function in "C++ Templates: The Complete Guide"
Hi all,
There's a type function that determine whether a type is a class in
the book. I do not understand it and it can not pass the compilation.
Here's the code:
// traits/isclasst.hpp
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 }; <===
Error reported here on VS2005 & GCC
enum { No = !Yes };
};
// traits/isclasst.cpp
#include <iostream>
#include "isclasst.hpp"
class MyClass {
};
struct MyStruct {
};
union MyUnion {
};
void myfunc()
{
}
enumE{e1}e;
// check by passing type as template argument
template <typename T>
void check()
{
if (IsClassT<T>::Yes) {
std::cout << " IsClassT " << std::endl;
}
else {
std::cout << " !IsClassT " << std::endl;
}
}
// check by passing type as function call argument
template <typename T>
void checkT (T)
{
check<T>();
}
int main()
{
std::cout << "int: ";
check<int>();
std::cout << "MyClass: ";
check<MyClass>();
std::cout << "MyStruct:";
MyStruct s;
checkT(s);
std::cout << "MyUnion: ";
check<MyUnion>();
std::cout << "enum: ";
checkT(e);
std::cout << "myfunc():";
checkT(myfunc);
}
What I confused is why the class type will match the member pointer
version instead of ellipsis version, as the ellipsis can match any
variables in any quantity. Not every class must have a int member, in
the preceding code, the size of MyClass is 1, but it has no such
member.
When I tried to run for testing, I found the code can't pass the
compilation.
In VS2005, the error is:
error C2783: 'IsClassT<T>::Two IsClassT<T>::test(...)' : could not
deduce template argument for 'C'
with
[
T=int
]
and in GCC4.0.0(fedora 4), the error is:
error: expected primary-expression before ">" token
Does anyone meet the same problem when reading this book? Any
suggestion or advice are appriciated.
Best Regards,
George Gui
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]