这段代码应该如何表现?如果我在函数中使用限定名,它会调用通用函数而忽略我的重载call_read()
;如果我使用非限定名称,它首先调用重载,然后调用通用版本。有什么不同?它是 GCC 中的错误吗?
#include <iostream>
struct info1 {};
struct info2 {};
template<class T> void read(T& x)
{
std::cout << "generic" << std::endl;
}
template<class T> void call_read(T& x)
{
::read(x); // if I replace ::read(x) with read(x) the overload is called
}
void read(info1& x)
{
std::cout << "overload" << std::endl;
}
int main()
{
info1 x;
info2 y;
call_read(x);
call_read(y);
}
我还注意到它对基本类型的工作方式不同。见下面的代码
#include <iostream>
typedef struct info1 {};
typedef struct info2 {};
typedef int info3;
typedef double info4;
template<class T> void read(T x)
{
std::cout << "generic" << std::endl;
}
template<class T> void call_read(T x)
{
read(x);
}
void read(info1 x)
{
std::cout << "overload" << std::endl;
}
void read(info3 x)
{
std::cout << "overload" << std::endl;
}
int main()
{
call_read(info1());
call_read(info2());
call_read(info3());
call_read(info4());
}
它应该调用两次重载函数,但事实并非如此。在此处查看结果 http://codepad.org/iFOOFD52