Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide function definition with enable_if [duplicate]

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.

like image 891
abraham_hilbert Avatar asked Aug 17 '26 00:08

abraham_hilbert


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()
like image 142
George Avatar answered Aug 19 '26 17:08

George



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!