Search code examples
c++c++11enable-if

How to have a member function implementation dependent on class' template parameter?


This is my best attempt:

#include <iostream>

template <bool EnableSomething = false>
class MyClass
{
    typename std::enable_if< EnableSomething >::type
        something(int& x)
    {
        x += 1; //do something
    }

    typename std::enable_if< !EnableSomething >::type
        something(int& x)
    {
        // do nothing, should be optimized away
    }

public:
    void Process()
    {
        int x = 0;
        something(x);
        std::cout << "Enabled: " << EnableSomething << ".  x = " << x << std::endl;
    }
};

int main()
{
    MyClass<true> yes;
    MyClass<false> no;
    yes.Process();
    no.Process();
    return 0;
}

The compiler says: tester.cpp(12): error C2039: 'type': is not a member of 'std::enable_if<false,_Ty>'


Solution

  • Make regular templates with default argument taken from parent tempalte:

    template<bool x_enabled = EnableSomething> 
    typename std::enable_if< x_enabled >::type
    something(int& x)
    {
        x += 1; //do something
    }
    
    template<bool x_enabled = EnableSomething> 
    typename std::enable_if< !x_enabled >::type
    something(int&)
    {
        // do nothing, should be optimized away
    }
    

    With c++17 things become simpler:

    void
    something(int& x)
    {
        if constexpr(EnableSomething)
        {
            x += 1; //do something
        }
    }