为什么std::stable_partition编译时没有明确的命名空间规范

Why does std::stable_partition compile without an explicit namespace specification

本文关键字:命名空间 stable std partition 为什么 编译      更新时间:2023-10-16

我在Ubuntu上工作

gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.2) 

以下代码是在cplusplus.com条目中提供的关于std::stable_partition

的示例

这不是一个确切的副本,但是,我从<algorithm>标头的std::stable_partition调用中删除了名称空间范围限定符(std::)。

我希望程序不能编译,当我简单地把它提供给g++:

$ g++ -Wall -std=c++14 sp_test.cpp 

但是,它编译时没有错误,甚至没有警告。

有人知道为什么吗?

似乎在algorithm的引擎盖下的某个地方写着using std::stable_partition

我是c++和g++的新手,所以我也想知道这是否是一个适当的问题,即我是否应该为这种(看似)违反g++预期行为而烦恼。

// stable_partition example
#include <iostream>     // std::cout
#include <algorithm>    // std::stable_partition
#include <vector>       // std::vector
bool IsOdd (int i) { return (i%2)==1; }
int main () {
        std::vector<int> myvector;
        // set some values:
        for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9
        std::vector<int>::iterator bound;
        bound = stable_partition (myvector.begin(), myvector.end(), IsOdd);
        // print out content:
        std::cout << "odd elements:";
        for (std::vector<int>::iterator it=myvector.begin(); it!=bound; ++it)
                std::cout << ' ' << *it;
        std::cout << 'n';
        std::cout << "even elements:";
        for (std::vector<int>::iterator it=bound; it!=myvector.end(); ++it)
                std::cout << ' ' << *it;
        std::cout << 'n';
        return 0;
}

这是因为依赖于参数的查找。您的实现碰巧在std命名空间中定义了std::vector<int>::iterator,因此查找stable_partition的名称隐式地在std中搜索。

这是不可移植的代码,因为std::vector<int>::iterator可能是在std中没有直接声明的某种类型的类型定义(它可能在嵌套的名称空间中,或者具有保留名称的名称空间中,或类似的东西),因此依赖参数的查找将不一定在std中搜索。