Hide function definition with enable_if

Viewed 574

Can someone help me to understand why the following code does not compile:

#include <type_traits>

class A{};
class B{};


template< typename T >
class C
{
  template< typename = std::enable_if_t<std::is_same<T, A>::value > >
  void foo()
  {}

  template< typename = std::enable_if_t<std::is_same<T, B>::value > >
  void foo()
  {}
};

error message:

t.cpp:15:8: error: class member cannot be redeclared
  void foo()
       ^
t.cpp:11:8: note: previous declaration is here
  void foo()
       ^
1 error generated.

I expected that always only one definition of foo is active; either the first one in case of T is equal to A and the second in case of T is equal to B.

It would be great if someone can help me to fix the code.

1 Answers

Directly from cppreference, emphasis mine:

A common mistake is to declare two function templates that differ only in their default template arguments. This is illegal because default template arguments are not part of function template's signature, and declaring two different function templates with the same signature is illegal.

In easier words, both the functions signature is:

template<typename>
void foo()
Related