这样的函数重载导致的歧义如何解决?
How to solve ambiguity caused by function overloading like this?
我有一段类似这样的代码:
#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&)
效率更高,但我不能使用文字常量作为参数,而 foo(T)
将适用于文字常量尽管它不如 foo(T&)
高效。但是当我定义这两个函数时,当 c.foo(a)
将要执行时会有一个模棱两可的调用。
error: call of overloaded 'foo(int&)' is ambiguous
我该如何克服这个问题?
您可以通过 const 引用 const T&
传递,这样它也将接受文字常量,或者通过右值引用 T&&
而不是 T
传递,这样它只接受右值(像文字常量)
我有一段类似这样的代码:
#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&)
效率更高,但我不能使用文字常量作为参数,而 foo(T)
将适用于文字常量尽管它不如 foo(T&)
高效。但是当我定义这两个函数时,当 c.foo(a)
将要执行时会有一个模棱两可的调用。
error: call of overloaded 'foo(int&)' is ambiguous
我该如何克服这个问题?
您可以通过 const 引用 const T&
传递,这样它也将接受文字常量,或者通过右值引用 T&&
而不是 T
传递,这样它只接受右值(像文字常量)