2

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

Dženan
  • 3,329
  • 3
  • 31
  • 44
  • 1
    This seems to be a good case for `if constexpr`, but in c++ 11 you will need to write regular member function templates. – user7860670 Mar 26 '18 at 18:26
  • 1
    Firstly, make sure you have `type_traits` included. Secondly, you cannot overload based on the return type. – LogicStuff Mar 26 '18 at 18:26
  • 1
    This is fundamentally wrong. SFINAE is based on argument deduction and substitution, thus "failure not a error". Here no deduction at all. – llllllllll Mar 26 '18 at 18:31
  • 1
    This shoudn't be marked as duplicate, little different question as can be seen from @VT_T's answer. – jbp Mar 26 '18 at 18:46

1 Answers1

2

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
    }
}
user7860670
  • 35,849
  • 4
  • 58
  • 84
  • With c++17 `something` is not needed. Just do `if constexpr` in `Process()`. `something` is a workaround for lack of `if constexpr`. – Dženan Mar 26 '18 at 19:33