This is a follow up to my question SFINAE with variadic templates. I was trying to construct a variadic template named has_member
for checking whether a class has a member (called member
).
I tried to see if I could use size_t
instead of void
in the answer to that question and not use variadic templates, as follows:
#include <iostream>
#include <vector>
using namespace std;
class ClassWithMember
{
public:
int member;
};
class ClassWithoutMember
{
};
template <typename T,typename=size_t>
class has_member: public std::false_type
{
};
template <typename T>
class has_member<T,decltype(sizeof(typename T::member))>: public std::true_type
{
};
template <typename T1,
std::enable_if_t<has_member<T1>::value>* = nullptr>
void my_function(const T1& obj) { cout<<"Function for classes with member"<<endl; }
template <typename T1,
std::enable_if_t<!has_member<T1>::value>* = nullptr>
void my_function(const T1& obj) { cout<<"Function for classes without member"<<endl; }
int main()
{
ClassWithMember objWithMember;
ClassWithoutMember objWithoutMember;
my_function (objWithMember);
my_function (objWithoutMember);
}
I get no errors, but the specialization is never used. Only the function for classes without the member gets called. Could someone please explain why?