c++ - 默认情况下,clang 中是否有一组已知的 `c++11` 功能不需要 `-std=c++11` ?

标签 c++ c++11 clang

clang (3.4) 似乎自动接受某些 c++11(例如 auto、for(:))而没有特殊标志(尽管产生警告),但不接受其他部分(< em>例如 lambdas).

例如下面编译clang++ c++11.success.cpp:

#include <vector>
int main( int argCount, char ** argVec )
{
    std::vector<int> vec;

    for( auto & item : vec )
    {
        ++item;
    }    

    return 0;
}

但这失败了clang++ c++11.failure.cpp:

#include <vector>
int main( int argCount, char ** argVec )
{
    std::vector<int> vec;
    auto lambda = [] ( int & foo ) { return ++foo; }; //This line fails at []

    for( auto & item : vec )
    {
        lambda( item );
    }

    return 0;
}

clang++ c++11.failure.cpp -std=c++11当然成功了。

我找不到任何关于在没有 -std=c++11 的情况下支持哪些 c++11 功能以及原因的具体文档。有人知道吗?

最佳答案

Clang 有(与任何其他 C++ 编译器一样)一些 language extensions (有一个 C++11 扩展列表,在 C++03 中可用)。这种扩展之一是基于范围的 for 循环。您可以通过 #if __has_extension(cxx_range_for) ... 对其进行测试。无论如何它都会产生一个警告(如果你没有用 -Wno-c++11-extensions 禁用它)。您可以使用以下方法测试这些功能:

#if __has_extension(cxx_range_for)
#warning __has_extension(cxx_range_for) is true
#else
#warning __has_extension(cxx_range_for) is false
#endif

#if __has_feature(cxx_range_for)
#warning __has_feature(cxx_range_for) is true
#else
#warning __has_feature(cxx_range_for) is false
#endif

#if __has_extension(cxx_auto_type)
#warning __has_extension(cxx_auto_type) is true
#else
#warning __has_extension(cxx_auto_type) is false
#endif

#if __has_feature(cxx_auto_type)
#warning __has_feature(cxx_auto_type) is true
#else
#warning __has_feature(cxx_auto_type) is false
#endif

int main()
{
        return 0;
}

奇怪的是,这警告说,类型推断扩展和功能已关闭,但它有效地编译了自动指针(我猜,这是因为 auto 作为存储类说明符的旧含义) :

main.cpp:2:2: warning: __has_extension(cxx_range_for) is true [-W#warnings]
#warning __has_extension(cxx_range_for) is true
 ^
main.cpp:10:2: warning: __has_feature(cxx_range_for) is false [-W#warnings]
#warning __has_feature(cxx_range_for) is false
 ^
main.cpp:16:2: warning: __has_extension(cxx_auto_type) is false [-W#warnings]
#warning __has_extension(cxx_auto_type) is false
 ^
main.cpp:22:2: warning: __has_feature(cxx_auto_type) is false [-W#warnings]
#warning __has_feature(cxx_auto_type) is false
 ^

要完全符合标准,您应该通过启用 -Werror 将警告视为错误。

关于c++ - 默认情况下,clang 中是否有一组已知的 `c++11` 功能不需要 `-std=c++11` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24513867/

相关文章:

c++ - 如何在没有 std::move 的情况下 move 临时对象

c++ - 为什么 __builtin_parity 是相反的?

c++ - Bullseye 与 MS 代码覆盖工具

c++ - 默认构造函数在不应该调用时被调用

c++ - 在 Mac 上将 GCC 4.4 与 NetBeans 集成

c++ - vs2012 rc 中基于范围的 for 循环

c++ - 在哪里放置重载<<code>?

c++ - 指向结构成员变量的指针

c++ - 在 clang 中显式调用伪析构函数

python - vim - 你让我无法找到合适的 Python 库