首页 > 解决方案 > 为什么对模板化函数有模棱两可的调用?

问题描述

我在 C++ 中创建模板时遇到问题。我正在为 mac 使用 xcode。

将 an 传递intswap函数时,我得到错误代码“模糊调用”。但是,传递strings 工作正常。这是为什么?

这是我的代码

#include <iostream>
#include <cmath>
using namespace std;

template <typename T>

void swap(T& c, T& d)
{
    T temp = c;
    c = d;
    d = temp;
}

int main()
{
    int a = 10;
    int b = 20;

    swap(a, b);                   // this is an error "ambiguous call"
    cout << a << "\t" << b;

    string first_name = "Bob";
    string last_name = "Hoskins";
    swap(first_name, last_name);  // this works

    cout << first_name << "\t" << last_name;

    return 0;
}

标签: c++

解决方案


你有using namespace std;哪个std::swap进入范围。这意味着swap您编写的模板与 冲突std::swap,并且当您将 2 个整数传递给它时,您会得到一个模棱两可的调用。

外卖:从不using namespace std;

swap有趣的部分是用 2 std::strings调用是有效的。那是因为for有一个专业化。专业化被认为是更好的匹配,所以它被称为而不是你自己的。std::swapstd::stringswap


推荐阅读