【问题标题】:more than one instance of function template matches the argument list多个函数模板实例与参数列表匹配
【发布时间】:2020-01-12 03:45:51
【问题描述】:
#include <iostream>
using std::cout;
using std::endl;

#include <string>
using std::string;

template <class T>
T max(T const& t1, T const& t2) {
    return t1 < t2 ? t2 : t1;
}

int main() {
    cout << max(1, 2) << endl;
    cout << max<double>(1.2, 2) << endl;
    string s1 = "hello";
    string s2 = "world";
 -->   cout << max(s1, s1) << endl;
}

在带箭头的那一行,它抱怨: "函数模板 "max" 的多个实例与参数列表匹配:-- 函数模板 "const _Tp &std::__1::max(const _Tp &__a, const _Tp &__b)"-- 函数模板 "T max(const T &t1, const T &t2)" -- 参数类型为:(std::__1::string, std::__1::string)"

我很困惑,因为它们都是字符串,不确定模板还能匹配什么。

【问题讨论】:

  • 与 std::max 冲突?如果更改名称会怎样?

标签: c++ templates


【解决方案1】:

max 函数与通过 ADL 找到的 std::max 函数冲突。要解决这个问题,您可以用合格的查找替换调用:

cout << ::max(s1, s1) << endl;

你也可以用括号括住函数名来禁用ADL:

cout << (max)(s1, s1) << endl;

整数没有命名空间,因此它们不受 ADL 约束,因此您没有看到这些问题。

【讨论】:

  • 但为什么不是整数呢?
  • 因为非类类型没有 ADL
猜你喜欢
  • 1970-01-01
  • 2012-10-12
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-09
  • 1970-01-01
相关资源
最近更新 更多