c++ - 为什么 "using namespace xxx"对模板函数不生效?

标签 c++ namespaces

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(名称查找)中所说的:

Name lookup shall find an unambiguous declaration for the name (see 10.2). Name lookup may associate more than one declaration with a name if it finds the name to be a function name; the declarations are said to form a set of overloaded functions (13.1). Overload resolution (13.3) takes place after name lookup has succeeded. The access rules (clause 11) are considered only once name lookup and function overload resolution (if applicable) have succeeded.

并且在 3.4.1(非限定名称查找)中:

name lookup ends as soon as a declaration is found for the name

在你的例子中,f是一个不合格的名字。它在直接范围和命名空间 ns2 中搜索在何处找到声明。名称查找到此结束,重载解析开始发挥作用:候选集中没有匹配参数类型 std::vector<int> 的重载。 , 所以这个程序是病式的。

关于c++ - 为什么 "using namespace xxx"对模板函数不生效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4448598/

相关文章:

c++ - “封闭”友元类的范围

c++ - libc++ 中的 `__gnu_cxx::temporary_buffer`?

extjs - Ext JS 3.2 Ext.namespace

php - 类是否只能对其命名空间可见

django - 基于请求命名空间解析 URL

java - TLD-first 类域标识符的重要性是什么?

c++ - 在构造函数中使用 std::vector 损坏内存

c++ - 在控制台应用程序中工作的计时器

c++ - vector 迭代器不是增量的

PHP Xpath 抓取可能的命名空间问题