【问题标题】:How to solve ambiguity caused by function overloading like this?如何解决这样的函数重载引起的歧义?
【发布时间】:2016-03-02 19:21:57
【问题描述】:

我有一段类似这样的代码:

#include <iostream>

using namespace std;

template<typename T>
class Class
{
public:
    Class() {}
    void foo(T)  {cout << "foo(T) is called \n";}
    void foo(T&) {cout << "foo(T&) is called \n";}
};

int main()
{
    Class<int> c;
    int a = 1;

    c.foo(1);
    c.foo(a);

    return 0;
}

我想要函数 foo 的两个重载,因为 foo(T&amp;) 效率更高,但我不能使用文字常量作为它的参数,foo(T) 将适用于文字常量,尽管它不如 @ 高效987654325@。但是当我定义这两个函数时,c.foo(a) 将要执行时会出现一个模棱两可的调用。

错误:重载 'foo(int&)' 的调用不明确

我该如何克服这个问题?

【问题讨论】:

  • 使用一个函数void foo(const T&amp;)

标签: c++ literals overloading ambiguous-call


【解决方案1】:

您可以通过 const 引用 const T&amp; 传递,这样它也将接受文字常量,或者通过右值引用 T&amp;&amp; 而不是 T 传递,以便它只接受右值(如文字常量)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    相关资源
    最近更新 更多