Juergen
Juergen

Reputation: 3743

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

Upvotes: 1

Views: 1092

Answers (2)

Quentin
Quentin

Reputation: 63124

Complement to findall's answer : you can also inherit from an easily specializable base class.

struct UseMap;
struct NoMap;

template<typename>
class MyClass;

namespace detail {
  // Container for the handleEvent() function
  template<typename>
  struct MyClassHandler;
}

// Enter CRTP !
template<typename MapType = NoMap>
class MyClass : detail::MyClassHandler<MyClass<MapType>>
{
    friend class detail::MyClassHandler<MyClass<MapType>>;
public:
  using detail::MyClassHandler<MyClass<MapType>>::handleEvent;

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

// Actual specializations now that the full definition of MyClass is in scope
namespace detail {
  template<>
  struct MyClassHandler<MyClass<NoMap>> {
    bool handleEvent(int someVal)
    {
      return static_cast<MyClass<NoMap>*>(this)->doSomething();
    }
  };

  template<>
  struct MyClassHandler<MyClass<UseMap>> {
    bool handleEvent(int someVal)
    {
      return static_cast<MyClass<UseMap>*>(this)->doSomethingDifferent();
    }
  };
}

I feel like I overcomplicated the declaration order a bit, double-check welcome :)

Upvotes: 1

findall
findall

Reputation: 2193

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)

Upvotes: 3

Related Questions