dimanche 12 septembre 2021

Why auto is not allowed in template function for creating a built-in array?

This code below does not compile:

template<typename... Ts>
void CreateArr(const Ts&... args)
{
    auto arr[sizeof...(args) + 1]{ args... };
}

int main()
{
    CreateArr(1, 2, 3);
}

due to the following errors:

  • 'arr': in a direct-list-initialization context, the type for 'auto [6]' can only be deduced from a single initializer expression
  • auto [6]': an array cannot have an element type that contains 'auto'
  • 'initializing': cannot convert from 'const int' to 'std::initializer_list<int>'

My questions are:

  • Why cannot I use auto to define the type of the array?

  • How to define it properly to work with the template?

Aucun commentaire:

Enregistrer un commentaire