jeudi 24 mars 2022

Initialize POD with two arrays using a factory function in C++11

I need to POD-initialize a struct of multiple arrays from a factory function. How do I forward its parameters to the brace-init list that is required to create the POD-struct (C++11)? I get this error:

<source>: In instantiation of 'constexpr generic_option<N, K> create_option(const int (&&)[N], const int (&&)[K]) [with long unsigned int N = 2; long unsigned int K = 2]':
<source>:209:32:   required from here
<source>:204:48: error: array must be initialized with a brace-enclosed initializer
  204 |     return generic_option<N, K>{to_wait, to_set};
      |                                                ^
<source>:204:48: error: array must be initialized with a brace-enclosed initializer
<source>:205:1: error: body of 'constexpr' function 'constexpr generic_option<N, K> create_option(const int (&&)[N], const int (&&)[K]) [with long unsigned int N = 2; long unsigned int K = 2]' not a return-statement
  205 | }
      | ^

My code:

template <size_t N, size_t K>
struct generic_option
{
    int to_wait_[N];
    int to_set_[K];
};

template <size_t N, size_t K>
constexpr generic_option<N, K> create_option(const int (&&to_wait)[N], const int (&&to_set)[K]) {
    return generic_option<N, K>{to_wait, to_set};
}

int main()
{
    create_option({1,4}, {2,3});
}

The reason for this post is that I can find information on how to initialize a struct of arrays with brace initializers using literals. But I can't seem to find a resource that states how to initialize them using compile time variables such as the ones passed to the factory function.

Aucun commentaire:

Enregistrer un commentaire