Home > Backend Development > C++ > body text

How to Use enable_if to Select Member Functions Based on Template Arguments?

Linda Hamilton
Release: 2024-10-26 12:44:29
Original
288 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!