Juergen Juergen - 2 months ago 17
C++ Question

SFINAE for class member overload methods

Consider this snippet:

#include <type_traits>

struct UseMap;
struct NoMap;

template<typename MapType = NoMap>
class MyClass
{
public:

typename std::enable_if<std::is_same<MapType, NoMap>::value, bool>::type
handleEvent(int someVal)
{
return doSomething();
}

typename std::enable_if<std::is_same<MapType, UseMap>::value, bool>::type
handleEvent(int someVal)
{
return doSomethingDifferent();
}

bool doSomething() {};
bool doSomethingDifferent() {};
};

int main() {
MyClass obj1();
MyClass<UseMap> obj2();
return 0;
}


Is it possible to compile only one
handleEvent
method, depending on the provided template class type?
With the example above the compiler gives:

prog.cpp:18:3: error: 'typename std::enable_if<std::is_same<MapType, UseMap>::value, bool>::type MyClass<MapType>::handleEvent(int)' cannot be overloaded

Answer

I think you have to make the overloaded functions template.

template<typename T = MapType,
  typename std::enable_if<
    std::is_same<T, NoMap>::value>::type *& = nullptr>
bool
handleEvent(int someVal)
{
  return doSomething();
}

template<typename T = MapType,
  typename std::enable_if<
    std::is_same<T, UseMap>::value>::type *& = nullptr>
bool
handleEvent(int someVal)
{
  return doSomethingDifferent();
}

This passes compile. (clang-600.0.54 with -std=c++11)