【发布时间】:2011-12-14 08:18:35
【问题描述】:
这段代码应该如何表现?如果我在 call_read() 函数中使用 qualified 名称,它会调用通用函数而忽略我的重载;如果我使用 unqualified 名称,它首先调用重载,然后调用通用版本。有什么不同?它是 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
【问题讨论】:
-
看起来很奇怪!其他问题:如果
call_read(T&)看不到read(info&),怎么会被调用? -
我不是,只是为了测试目的。我看到它的行为基于它的调用方式而有所不同。这很有趣。
-
我认为@iammilind 有所作为。如果您更改顺序并且
read的重载版本出现在call_read之前,它将按预期工作。我不知道为什么没有::它确实会调用重载(这似乎是错误)。
标签: c++ templates lookup language-lawyer argument-dependent-lookup