c++ - 使用 enable_if 的多个重载问题

标签 c++ templates c++17 sfinae template-specialization

这个问题在这里已经有了答案:





Problem with basic usage of std::enable_if

(1 个回答)


2年前关闭。



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'd 键入默认参数。相反,您可以使其解析为某种类型,例如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;
}

关于c++ - 使用 enable_if 的多个重载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61312426/

相关文章:

c++ - UWP - ListView 绑定(bind)不显示在 C++/CX 中的 XAML 上

c++ - LoadLibrary 失败,错误代码为 193

C++ 继承 : Can't access private element of base class

c++ - 调用我的模板操作符 << 只有在没有找到其他操作符时

C++是在每个实例化时创建的模板类中每个方法的新版本

c++ - 指向模板类的指针

c++ - 函数调用如何给出编译时类型?

c++ - 如何在 C++ 中生成任意嵌套的 vector ?

c++ - 为整数序列的每个参数调用一个 void 函数

c++ - 接口(interface)和实现 C++