繁体   English   中英

为什么在没有显式命名空间规范的情况下编译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的示例

这不是完全相同的副本然而,我去掉了命名空间范围限定符( std::从呼叫到) std::stable_partition所述的<algorithm>头。

我希望将程序简单地馈送到g ++时,程序不会编译:

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

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

有人知道为什么吗?

似乎已经using std::stable_partition在该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可能是某种类型的typedef,而该类型的typedef并未在std内部直接声明(它可能在嵌套的名称空间中,或者在具有保留名称的名称空间中,或者类似的东西)这样),因此依赖于参数的查找不一定会在std内部进行搜索。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM