Open In App

How to Check if a Template Class has the Given Member Function in C++?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to check whether a templated class has a
// member function or not.
  
#include <iostream>
using namespace std;
  
// Define a template class 'temp'
template <typename T> class temp {
public:
    // Member function 'func' that returns a bool
    bool func(const T& element) { return true; }
};
  
// Define a template class 'check' to test for the existence
// of 'func'
template <typename T> class check {
    // Define two types of character arrays, 'yes' and 'no',
    // for SFINAE test
    typedef char yes[1];
    typedef char no[2];
  
    // Test if class T has a member function named 'func'
    // If T has 'func', this version of test() is chosen
    template <typename C>
    static yes& test(decltype(&C::func));
  
    // Fallback test() function used if T does not have
    // 'func'
    template <typename> static no& test(...);
  
public:
    // Static constant 'value' becomes true if T has 'func',
    // false otherwise The comparison is based on the size
    // of the return type from test()
    static const bool value
        = sizeof(test<T>(0)) == sizeof(yes);
};
  
int main()
{
    // Test if 'temp<int>' has a member function 'func'
    cout << boolalpha << check<temp<int> >::value
         << endl; // Outputs true
  
    // Test if 'temp<double>' has a member function 'func'
    cout << boolalpha << check<temp<double> >::value
         << endl; // Outputs true
  
    return 0;
}


Output

true
true



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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads