An example described in book C++ Templates The Complete Guide:
template <typename T>
class IsClass {
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(IsClass<T>::test<T>(0)) == 1)
};
enum {
No = !Yes
};
};
I've read related topic Where can I find a description about the usage of "int C::*"? I've got the concept that C::* means a pointer to member, and test(0) means test(nullptr), but I have some other questions:
- Suppose the compiler does not check if the class C really has a member of type int. Why compiler does not check?
- The int type in int C::* could be replaced by any type but void, although I think void is less confusing. Why this error reported?
In file included from testisclass.cpp:12:
../inc/isclass.hpp:17:54: error: cannot declare pointer to ‘void’ member
17 | template<typename C> static One test(void C::*);
| ^
../inc/isclass.hpp: In instantiation of ‘class IsClass<A>’:
testisclass.cpp:22:16: required from here
../inc/isclass.hpp:17:41: error: creating pointer to member of type void
17 | template<typename C> static One test(void C::*);
| ^~~~
../inc/isclass.hpp: In instantiation of ‘class IsClass<int>’:
testisclass.cpp:28:18: required from here
../inc/isclass.hpp:17:41: error: creating pointer to member of type void
- Yes = true/false is a complete definition, why still No defined?