most vexing parse prevents in-class initializing a std::vector

后端 未结 1 529
-上瘾入骨i
-上瘾入骨i 2020-12-11 02:43

C++11 allows in-class initialization:

struct Foo{
    std::vector v{3}; // vector of 3 empty strings
};

If we wanted to

相关标签:
1条回答
  • 2020-12-11 03:27

    Default member initializers work with = as well. So

    struct Foo{
        std::vector<int> v = std::vector<int>(3);
    };
    

    Will do it. Though obviously, a major caveat is the fact that we are repeating the type name here.

    We can alleviate it somewhat with decltype:

    struct Foo{
        std::vector<int> v = decltype(v)(3);
    };
    

    But that still has us naming things twice.

    0 讨论(0)
提交回复
热议问题