使用 enable_if 的多个重载问题

Issue with multiple overloads using enable_if

template <typename T,  typename = enable_if_t<is_same<T, int>::value>>
void qw(T t) 
{
  std::cout << "int " << endl;
}

template <typename T , typename =  enable_if_t<is_same<T, float>::value>>
void qw(T t) 
{
   cout << "float" << endl;
}

// Invoked from main as 
int main()
{
   int x = 10;
   qw(x);
}

我在 g++9.2 中遇到的错误

sp.cc:153:6: error: redefinition of ‘template<class T, class> void qw(T)’
  153 | void qw(T t)
      |      ^~
sp.cc:147:6: note: ‘template<class T, class> void qw(T)’ previously declared here
  147 | void qw(T t)

我假设只有一个重载格式正确并且会被选中。但是它抱怨多个定义。有人可以帮忙解释为什么吗?

来自 cppreference,其中有这个例子作为注释:

A common mistake is to declare two function templates that differ only in their default template arguments. This does not work because the declarations are treated as redeclarations of the same function template (default template arguments are not accounted for in function template equivalence).

所以您需要做的是不要将 sfinae 类型设为默认参数。相反,您可以将其解析为某种类型,例如int,并给它一个默认值,像这样:

template <typename T, enable_if_t<is_same_v<T, int>, int> = 0>
void qw(T t)  
{
  std::cout << "int " << endl;
}

template <typename T, enable_if_t<is_same_v<T, float>, int> = 0>
void qw(T t) 
{
   cout << "float" << endl;
}