static std :: array,其结构包含std :: string

时间:2017-05-21 12:20:20

标签: c++ arrays c++11 static

我正在尝试创建一个查找表,以便轻松创建具有不同值的对象。为此,我需要在我的类中使用一个静态std :: array来填充数据。 它目前看起来像这样:

#include <iostream>

#include <array>
#include <string>

struct MyStruct{
    std::string s;
    int a;
    int b;
};

class Arr{
public:
    static constexpr std::array<MyStruct, 3> strArray{{{"a", 1,2}, {"b", 2,3}, {"c", 3,4}}};
};

constexpr std::array<MyStruct, 3> Arr::strArray;

int main()
{    
    for(auto i : Arr::a){
        std::cout << i << std::endl;
    }

    std::cout << "With a struct:\n";
    for(auto i : Arr::strArray){
        std::cout << i.a << ", " << i.b << std::endl;
    }



    return 0;
}

它工作正常,如果我删除std :: string,但是使用std :: string我得到编译错误

../staticArray/main.cpp:15:46: error: constexpr variable cannot have non-literal type 'const std::array<MyStruct, 3>'
    static constexpr std::array<MyStruct, 3> strArray{{{"a", 1,2}, {"b", 2,3}, {"c", 3,4}}};
                                             ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/array:137:16: note: 'array<MyStruct, 3>' is not literal because it has data member '__elems_' of non-literal type 'value_type [3]'
    value_type __elems_[_Size > 0 ? _Size : 1];
               ^
../staticArray/main.cpp:19:40: error: constexpr variable cannot have non-literal type 'const std::array<MyStruct, 3>'
constexpr std::array<MyStruct, 3> Arr::strArray;
                                       ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/array:137:16: note: 'array<MyStruct, 3>' is not literal because it has data member '__elems_' of non-literal type 'value_type [3]'
    value_type __elems_[_Size > 0 ? _Size : 1];

2 个答案:

答案 0 :(得分:1)

在C ++ 17中,您可以使用std::string_view代替std::stringhttp://coliru.stacked-crooked.com/a/946c48ee9f87a363

出于某种原因,虽然你不能使用构造函数(在string_view中)只接受const char *(它应该是可能的,因为它是constexpr)所以它也需要传递长度。

在C ++ 11中,它可以做同样的事情,但你必须自己制作std :: string_view类

答案 1 :(得分:-1)

(从评论部分迁移)

  

该错误表明[none] of the string constructors [are] constexpr的事实。它们怎么能用于动态内存分配的类型呢? Your table cannot be constexpr if you want to use std::string. (用户StoryTeller