我有以下代码:
#include <iostream>
template <typename T>
void f(T& x)
{
std::cout << "f(T& )" << std::endl;
}
template <typename T>
void f(const T& x)
{
std::cout << "f(const T& )" << std::endl;
}
int main()
{
int a = 0;
const float b = 1.1;
f(a); // call f(T&)
f(b); // call f(const T&)
}
输出结果为:
f(T& )
f(const T& )
我的问题是:编译器如何知道调用哪个函数?如果我从函数定义中删除了引用,那么就会出现"模糊的调用"类型的错误,即 error: redefinition of 'f'
。对我来说,看起来f(T&)
可以同样适用于两种调用,为什么const
版本在f(b)
中被明确地调用?
f(b)
,其中b
是一个const float
时,它将调用f()
的const变体。 - Alex