"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Select a Member Function Based on a Template Parameter Using `enable_if`?

How to Select a Member Function Based on a Template Parameter Using `enable_if`?

Published on 2024-11-06
Browse:343

How to Select a Member Function Based on a Template Parameter Using `enable_if`?

Selecting a Member Function Using Enable_If Conditions

The task is to determine the invocation of a member function based on a class template parameter. The following code snippet attempts to achieve this:

#include 
#include 

template
struct Point
{
  void MyFunction(typename std::enable_if<:is_same int>::value, T &>::type* = 0)
  {
    std::cout ::value, float &>::type* = 0)
  {
    std::cout 

However, this code fails to compile with the error "no type named ‘type’ in ‘struct std::enable_if’".

SFINAE in Action

The key to understanding this issue lies in the concept of Substitution Failure Is Not An Error (SFINAE). Enable_if allows conditional compilation based on template arguments. In this case, the template argument T is already known when the member functions are instantiated. Therefore, the condition is evaluated at instantiation time and the corresponding function is selected.

Fixing the Code

To rectify this, we need to introduce a dummy template argument that is defaulted to T. This allows the SFINAE mechanism to work as intended. The modified code would look like this:

template
struct Point
{
  template
  typename std::enable_if<:is_same int>::value>::type
    MyFunction()
  {
    std::cout 
  typename std::enable_if<:is_same float>::value>::type
    MyFunction()
  {
    std::cout 

Preventing Explicit Member Function Specialization

As pointed out by HostileFork, the original code allows the explicit specification of template arguments for the member functions, which could lead to incorrect results. To prevent this, we can add a static_assert that checks if any template arguments are provided. This ensures that the correct member function is always invoked based on the template argument T. The modified code would be:

template
struct Point
{
  template
  typename std::enable_if<:is_same int>::value>::type
    MyFunction()
  {
    static_assert(sizeof...(Dummy)==0, "Do not specify template arguments!");
    std::cout 
  typename std::enable_if<:is_same float>::value>::type
    MyFunction()
  {
    static_assert(sizeof...(Dummy)==0, "Do not specify template arguments!");
    std::cout 
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3