Home >Backend Development >C++ >How to Use enable_if to Select Member Functions Based on Template Arguments?
Selecting a Member Function Using Different enable_if Conditions
The enable_if metafunction is utilized to specify template function parameters and select appropriate member functions based on them. Consider the following code:
<code class="cpp">template<typename T> struct Point { // Check if T is int and call MyFunction for int void MyFunction(typename std::enable_if<std::is_same<T, int>::value, T &>::type* = 0) { std::cout << "T is int." << std::endl; } // Check if T is not int and call MyFunction for non-int void MyFunction(typename std::enable_if<!std::is_same<T, int>::value, float &>::type* = 0) { std::cout << "T is not int." << std::endl; } };</code>
However, this code may cause compiler errors indicating that "no type named ‘type’ in ‘struct std::enable_if’".
Understanding enable_if
enable_if ensures that only viable function overloads are considered during overload resolution. If a template argument substitution fails, that overload is removed from the candidate set.
In the example above, the template argument T is already known when instantiating the member functions. To implement the desired behavior, we can create a dummy template argument defaulted to T and perform SFINAE using it:
<code class="cpp">template<typename T> struct Point { template<typename U = T> typename std::enable_if<std::is_same<U, int>::value>::type MyFunction() { std::cout << "T is int." << std::endl; } template<typename U = T> typename std::enable_if<std::is_same<U, float>::value>::type MyFunction() { std::cout << "T is not int." << std::endl; } };</code>
The above is the detailed content of How to Use enable_if to Select Member Functions Based on Template Arguments?. For more information, please follow other related articles on the PHP Chinese website!