2012-06-12 105 views
11

今天Apple更新Xcode的命令行工具,然后将318.0.58的clang升级到318.0.61。Clang中的初始化程序列表

我试过使用初始化列表,但不能编译下面的代码。

#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; 
    } 
} 

然后,我试着编译。

错误日志

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++ -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 

回答

11

尝试通过指定-std=c++0x(如@jweyrich正确地指出)作为clang命令线的一部分。 clang的默认值是C++ 98模式。初始化程序列表是一个C++ 11功能。

此外,从铿锵C++ 98和C++ 11 support page您可以检查各种新的C++标准功能的状态。例如,初始化程序列表在3.1(及以上)中可用。

+0

苹果铛不能识别'-std = C++ 11' – user1214292

+1

@ user1214292:它承认'-std = C++ 0x'虽然。 – jweyrich

+0

@jweyrich但结果将保持不变:( – user1214292

7

编译使用命令:

clang++ -stdlib=libc++ -std=c++0x foo.cpp 

注意-std=c++11也适用。在我的机器上运行:

$ clang --version 

结果:

Apple clang version 4.1 (tags/Apple/clang-421.11.66) (based on LLVM 3.1svn) 
Target: x86_64-apple-darwin12.2.0 
相关问题