为什么std::stable_partition编译时没有明确的命名空间规范
Why does std::stable_partition compile without an explicit namespace specification
我在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
中搜索。
相关文章:
- 命名空间中具有.h和.cpp文件的类
- 从父命名空间重载类型
- 在命名空间中定义函数还是限定函数
- C++:对不存在的命名空间使用命名空间指令
- 通过继承类使用来自不同命名空间的运算符
- 使用命名空间时出现多个定义错误
- CUDA内核和数学函数的显式命名空间
- 嵌套的匿名命名空间
- CMakeLists.txt中的命名空间表示法
- 类是C++中的命名空间吗
- 在命名空间中使用全局命名空间中的函数
- 如何使 std::sort 在 std::swap 和我的命名空间的模板化交换之间没有名称冲突?
- '使用命名空间{嵌套在另一个命名空间中的某个命名空间}"
- 是否可以将函数导入命名空间,但不能导出它?
- C++ C++类中的命名空间降级
- 如何使用 soong 命名空间来有条件地编译模块
- 使用 Clang++ 有没有办法将文件作为命名空间等包含?
- 使用 make 编译 MPI,几个命名空间错误,例如"错误:未知类型名称'使用'?
- 如何通过命名空间调用非静态方法
- 在命名空间名称之前加上 :: 是什么意思?