Home > Article > Backend Development > Why Does SFINAE Fail to Detect Inherited Member Functions?
Inheriting Member Function Detection with SFINAE
SFINAE (Substitution Failure Is Not an Error) allows for the detection of member functions within a given class. However, when applied to inherited member functions, SFINAE encounters limitations, resulting in false detections.
To illustrate this issue, consider the following code:
<code class="cpp">// Does not correctly detect inherited member functions template<typename T, typename Sig> struct has_foo { template <typename U, U> struct type_check; template <typename V> static char (& chk(type_check<Sig, &V::foo>*))[1]; template <typename > static char (& chk(...))[2]; static bool const value = (sizeof(chk<T>(0)) == 1); }; struct A { void foo(); }; struct B : A {}; int main() { using namespace std; cout << boolalpha << has_foo<A, void (A::*)()>::value << endl; // true cout << boolalpha << has_foo<B, void (B::*)()>::value << endl; // false }
In this example, has_foo fails to detect the inherited foo() member in B from A.
To overcome this limitation, a more refined SFINAE technique is required. Consider the following solution:
<code class="cpp">template <typename Type> class has_foo { class yes { char m;}; class no { yes m[2];}; struct BaseMixin { void foo(){} }; struct Base : public Type, public BaseMixin {}; template <typename T, T t> class Helper{}; template <typename U> static no deduce(U*, Helper<void (BaseMixin::*)(), &U::foo>* = 0); static yes deduce(...); public: static const bool result = sizeof(yes) == sizeof(deduce((Base*)(0))); }; // Usage struct A { void foo(); }; struct B : A {}; struct C {}; int main() { using namespace std; cout << boolalpha << has_foo<A>::result << endl; cout << boolalpha << has_foo<B>::result << endl; cout << boolalpha << has_foo<C>::result; }</code>
Result:
true true false
This solution introduces a base mix-in class, BaseMixin, which provides the foo() member function. Inherited member functions are detected by checking the existence of foo() in the mix-in class. This technique allows for accurate detection of inherited member functions, including those inherited multiple levels deep.
The above is the detailed content of Why Does SFINAE Fail to Detect Inherited Member Functions?. For more information, please follow other related articles on the PHP Chinese website!