Home > Article > Backend Development > How to Detect Inherited Member Functions Using SFINAE?
SFINAE for Detecting Inherited Member Functions
Inherent member functions can be detected using Substitution Failure Is Not An Error (SFINAE) techniques. However, standard SFINAE implementations may fall short. This article explores a workaround solution to detect inherited member functions.
Consider the following code:
<code class="cpp">#include <iostream> 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 }</code>
This code utilizes SFINAE to detect member functions. However, it fails to detect inherited member functions in B.
To address this, the following codebase can be used:
<code class="cpp">#include <iostream> 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))); }; 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>
This version utilizes class inheritance and defines a helper class to assist in the SFINAE check. The result output demonstrates the successful detection of inherited member functions.
The above is the detailed content of How to Detect Inherited Member Functions Using SFINAE?. For more information, please follow other related articles on the PHP Chinese website!