निम्न कोड एक SFINAE कार्यान्वयन को यह दिखाने के लिए दिखाता है कि एक प्रकार (मूल रूप से एक वर्ग) में सदस्य कार्य member_func
संकलन समय पर है।SFINAE दृष्टिकोण तुलना
#define CHECKER(func_name,class_name) sizeof(class_name<T>::template func_name<T>(0)) == 1
#include <iostream>
struct A
{
void member_func();
};
struct B {};
template<typename T>struct Check_If_T_Is_Class_Type
{
template<typename C> static char func (char C::*p);
template<typename C> static long func (...);
enum{val = CHECKER(func,Check_If_T_Is_Class_Type)};
};
//APPROACH 1
template <typename T>struct TypeHasMemberFunc
{
template <typename C, C> struct TypeCheck;
template <typename C> struct Prototype_Holder {typedef void (C::*fptr)();};
template <typename C> static char func(TypeCheck
<
typename Prototype_Holder<C>::fptr,
&C::member_func
>*);
template <typename C> static long func(...);
enum {value = CHECKER(func,TypeHasMemberFunc)};
};
//APPROACH 2
template <typename T>struct has_member_func
{
template<class C> static char func(char (*)[sizeof(&C::member_func)]);
template<class C> static long func(...);
enum{value = CHECKER(func,has_member_func)};
};
int main(){
if(Check_If_T_Is_Class_Type<A>::val)
std::cout<<TypeHasMemberFunc<A>::value; //using APPROACH 1
if(Check_If_T_Is_Class_Type<B>::val)
std::cout<<has_member_func<B>::value; //using APPROACH 2
}
हालांकि मेरा प्रश्न यह है कि आप कौन सा दृष्टिकोण पसंद करेंगे (एप्रोच 1 या एप्रोच 2) और क्यों?
क्या आपको दिए गए दृष्टिकोणों में कोई असंगतता मिलती है? यदि हां कृपया मुझे बताएं।
पी.एस: मान लीजिए sizeof(char)!= sizeof(long)
परामर्श भी http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence/3627243#3627243। इसमें कुछ बहुत अच्छे जवाब हैं। – FireAphis