c++ - Clang 中的初始化列表

标签 c++ c++11

今天 Apple 更新了 Xcode 的命令行工具,然后将 clang 从 318.0.58 升级到 318.0.61。

我尝试使用初始化列表,但无法编译下面的代码。

#include <iostream>
#include <random>
#include <initializer_list>

int main()
{
    std::mt19937 rng(time(NULL));

    std::initializer_list<double> probabilities =
    {
        0.5, 0.1, 0.1, 0.1, 0.1, 0.1
    };

    std::discrete_distribution<> cheat_dice (probabilities);

    int a[6] = { };

    for ( int i = 0 ; i != 1000; ++i )
    {
        ++a[cheat_dice(rng)];
    }

    for ( int i = 0; i != 6; ++i )
    {
        std::cout << i + 1 << "=" << a[i] << std::endl;
    }
}

然后,我尝试编译。

$ clang++ -stdlib=libc++ foo.cpp

错误日志

foo.cpp:9:10: error: no member named 'initializer_list' in namespace 'std'
    std::initializer_list<double> probabilities =
    ~~~~~^
foo.cpp:9:33: error: expected '(' for function-style cast or type construction
    std::initializer_list<double> probabilities =
                          ~~~~~~^
foo.cpp:9:35: error: use of undeclared identifier 'probabilities'
    std::initializer_list<double> probabilities =
                                  ^
foo.cpp:10:5: error: expected expression
    {
    ^
foo.cpp:14:46: error: use of undeclared identifier 'probabilities'
    std::discrete_distribution<> cheat_dice (probabilities);
                                             ^
5 errors generated.

另一方面,我可以使用 gcc-4.7.1-RC-20120606 编译上述代码。

$ g++ -std=c++11 foo.cpp

Apple 的 clang 不支持初始化列表吗? Clang 版本:

$ clang++ -v
Apple clang version 3.1 (tags/Apple/clang-318.0.61) (based on LLVM 3.1svn)
Target: x86_64-apple-darwin11.4.0
Thread model: posix

最佳答案

尝试将 -std=c++0x (正如@jweyrich 正确指出的那样)指定为 clang 命令行的一部分。 clang 的默认值是 C++98 模式。初始化列表是 C++11 的一个特性。

另外,来自 C++98 和 C++11 的 clang support page您可以检查各种新 C++ 标准功能的状态。例如,初始化列表在 3.1(及更高版本)中可用。

关于c++ - Clang 中的初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10991274/

相关文章:

C++ union/结构位域实现和可移植性

c++ - 定义另一组宏的多行宏

c++ - 插入失败时列表/ map 返回什么?

c++ - 返回 std:vector 与 std::async c++11

C++ 可变参数模板总和

c++ - C++11 中的可变参数模板特化

c++ - 图节点父列表中的 weak_ptr VS shared_ptr

c++ - 将glade文件与程序g++链接

c++ - 如何提示用户输入字符或数字?

c++ - 如何将特定回调传递给模板函数?