How to fill array with contents of a template parameter pack?

≡放荡痞女 提交于 2019-12-05 11:52:42

Is a solution not based on template recursion acceptable in your use case? wandbox link

template <typename T, std::size_t Size>
struct Array {
    T data[Size];

    template <typename ...Args>
    constexpr Array(const Args&... args) : data{args...} {

    }
};

int main() {
    Array<int, 2> c(42, -18);
    assert(c.data[0] == 42);
    assert(c.data[1] == -18);

    constexpr Array<int, 2> cc(42, -18);
    static_assert(cc.data[0] == 42);
    static_assert(cc.data[1] == -18);
}

I might be off target here but based on this requirement "... I would like to fill an array at compile-time given a fixed set of parameters." and this code:

int main() {
Array<int, 2> c(42, -18);
return 0;
}

I have been left wondering is this not solvable with a normal array declaration and initialization?

    int main() {
        constexpr  int c []{42, -18};
        static_assert( c[0] == 42 ) ;
        // and so on
      return 0;
    }

In a comment to the previous answer, you are mentioning some setter? There must be something missing in here... In case you need to have this class Array as above, perhaps the simplest way to do so is this:

template<typename T, T ... V >
struct Array
{
  constexpr static T data_[]{ V... };
  // not strictly necessary
  constexpr static size_t size{ sizeof(data_) / sizeof(T) };
};

Usage is this:

  // length is not required for declaration
  using int_array_of_4 = Array<int,1,2,3,4> ;
  static_assert( int_array_of_4::data_[0] == 1) ;
  // and so on

But I might be barking on the wrong tree here?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!