How to Check if a Template Class has the Given Member Function in C++?
Last Updated :
31 Jan, 2024
In C++ programming, we often need to check if a template class contains a specific member function. In this article, we will discuss how to check if a Template Class has the given member function or not.
Check for the Member Function in a Template Class
We can check whether a member function exists in the template class or not by using SFINAE along with the type traits feature of C++. SFINAE is a technique used in C++ template programming that allows a function template specialization to be ignored if its template argument fails to substitute correctly. This technique is mainly used for creating type traits or to perform compile-time introspection.
C++ Program to Check for a Member Function in a Template Class
The following example demonstrates how we can check whether a template class has a member function or not.
C++
#include <iostream>
using namespace std;
template < typename T> class temp {
public :
bool func( const T& element) { return true ; }
};
template < typename T> class check {
typedef char yes[1];
typedef char no[2];
template < typename C>
static yes& test( decltype (&C::func));
template < typename > static no& test(...);
public :
static const bool value
= sizeof (test<T>(0)) == sizeof (yes);
};
int main()
{
cout << boolalpha << check<temp< int > >::value
<< endl;
cout << boolalpha << check<temp< double > >::value
<< endl;
return 0;
}
|
Explanation: In the above example, we use a technique called SFINAE (Substitution Failure Is Not An Error) to check if a templated class temp contains a member function func. This is achieved using a helper class check. check differentiates between types with and without func using two test functions and the sizeof operator. This method determines if func exists in temp for different types like int and double, as demonstrated in the main function.
Share your thoughts in the comments
Please Login to comment...