【问题标题】:Is it possible to have a std::array member whose size is unkown but evaluated at compile time? [closed]Is it possible to have a std::array member whose size is unkown but evaluated at compile time? [closed]
【发布时间】:2022-12-01 14:33:07
【问题描述】:

std::get's index is not known, but evaluated at compile time. I want to do something very similar to std::get's functionality with an std::array member.

Take this struct:

template<size_t size>
struct ArrayWrapper {
   std::array<int, size> arr;
};

I would want to be able to do something like this: ArrayWrapper&lt;4&gt; foo; Here, arr inside foo would be initialized at compile time with a size of 4. The code above doesn't work, which doesn't make sense to me since size is known at compile time.

Is there any way of making this work?

【问题讨论】:

  • Your corrected code compiles for me.

标签: c++ compile-time


【解决方案1】:

Note the corrected order of template arguments

template<size_t size>
struct ArrayWrapper {
   std::array<int, size> arr;
};

【讨论】:

    【解决方案2】:

    The template argument for std::array are reversed in your code. It should instead be:

    template<size_t size>
    struct ArrayWrapper {
    //------------vvv--vvvv----------->note the order is changed here
       std::array<int, size> arr;
    };
    
    int main()
    {
        ArrayWrapper<4> obj; //works
    }
    

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2022-12-02
      • 2020-06-24
      • 2022-12-02
      • 2022-12-28
      • 2019-09-21
      • 1970-01-01
      • 2022-12-02
      • 2022-12-01
      相关资源
      最近更新 更多