[英]Why does “using namespace xxx” not take effect on template functions?
namespace ns1
{
template <class T>
void f(T)
{
cout << typeid(T).name() << endl;
}
};
using namespace ns1;
namespace ns2
{
void f(int)
{
cout << "int" << endl;
}
void test()
{
f(vector<int>()); // Error!
// Why not call ns1::f<vector<int>>(vector<int>()); ???
}
};
这与模板无关,但没有名称查找。
这是标准在3.4 / 1(名称查找)中所说的内容:
名称查找应找到名称的明确声明(见10.2)。 如果名称查找名称是函数名称,则名称查找可以将多个声明与名称相关联; 据说声明形成一组重载函数(13.1)。 名称查找成功后,将发生重载分辨率(13.3)。 访问规则(第11节)仅在名称查找和功能重载解析(如果适用)成功后才被考虑。
并在3.4.1(非限定名称查找):
一旦找到名称的声明,名称查找就会结束
在您的情况下, f
是一个不合格的名称。 它在直接范围内搜索,并在名称空间ns2
中搜索, 其中包含声明 。 名称查找在此处结束,并且重载决策起作用:候选集中没有与参数类型std::vector<int>
匹配的重载,因此程序格式错误。
因为当您在命名空间(ns2)中时,如果名称不合格,则它优先于任何其他命名空间。
ns2将具有优先级,因为这是您当前所在的命名空间。为什么编译器认为您的确意味着ns1 :: f()?
这应该工作:
namespace ns1
{
template <class T>
void f(T)
{
cout << typeid(T).name() << endl;
}
};
namespace ns2
{
using ns1::f;
void f(int)
{
cout << "int" << endl;
}
void test()
{
f(vector<int>()); // Error!
// Why not call ns1::f<vector<int>>(vector<int>()); ???
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.