I am trying to apply the method described at http://www.drdobbs.com/tools/227500449
With the sample code below, I expect output:
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
And this is really what will happen if I compile using clang. But with gcc, this code gives the following errors:
junk.cpp: In instantiation of βconst bool has_foo_member_variable<B>::valueβ:
junk.cpp:45:5: instantiated from βvoid print() [with T = B]β
junk.cpp:82:14: instantiated from here
junk.cpp:30:75: error: βB::fooβ is not a valid template argument for type βint B::*β
junk.cpp:30:75: error: it must be a pointer-to-member of the form `&X::Y'
junk.cpp: In instantiation of βconst bool has_foo_member_variable<D>::valueβ:
junk.cpp:45:5: instantiated from βvoid print() [with T = D]β
junk.cpp:84:14: instantiated from here
junk.cpp:30:75: error: β& D::fooβ is not a valid template argument for type βint D::*β
junk.cpp:30:75: error: it must be a pointer-to-member of the form `&X::Y'
I am using gcc 4.5.1 ... I look like gcc does not follow the correct SFINAE rules, but I'm not 100% sure. Is this correct clang? Is this a gcc error?
#include <iostream>
struct small_type { char dummy; };
struct large_type { char dummy[2]; };
template<class T>
struct has_foo_member_function
{
template<int (T::*)()> struct tester;
template<class U> static small_type has_foo(tester<&U::foo> *);
template<class U> static large_type has_foo(...);
static const bool value = (sizeof(has_foo<T>(0)) == sizeof(small_type));
};
template<class T>
struct has_foo_static_member_function
{
template<int (*)()> struct tester;
template<class U> static small_type has_foo(tester<&U::foo> *);
template<class U> static large_type has_foo(...);
static const bool value = (sizeof(has_foo<T>(0)) == sizeof(small_type));
};
template<class T>
struct has_foo_member_variable
{
template<int T::*> struct tester;
template<class U> static small_type has_foo(tester<&U::foo> *);
template<class U> static large_type has_foo(...);
static const bool value = (sizeof(has_foo<T>(0)) == sizeof(small_type));
};
template<class T>
struct has_foo_static_member_variable
{
template<int *> struct tester;
template<class U> static small_type has_foo(tester<&U::foo> *);
template<class U> static large_type has_foo(...);
static const bool value = (sizeof(has_foo<T>(0)) == sizeof(small_type));
};
template<class T>
void print()
{
std::cout << has_foo_member_function<T>::value << " "
<< has_foo_static_member_function<T>::value << " "
<< has_foo_member_variable<T>::value << " "
<< has_foo_static_member_variable<T>::value << "\n";
}
struct A
{
int foo()
{
return 0;
}
};
struct B
{
static int foo()
{
return 0;
}
};
struct C
{
int foo;
};
struct D
{
static int foo;
};
int main()
{
print<A>();
print<B>();
print<C>();
print<D>();
}
source
share