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

Time:09-17

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?

CodePudding user response:

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

For the same reason, following does not work/ allowed!

auto ele[]{ 1, 2, 3 };

More reads: Why can't I create an array of automatic variables?


How to define it properly to work with the template?

Use the std::common_type_t for specifying the type

#include <type_traits> //  std::common_type_t

template<typename... Ts>
void CreateArr(const Ts&... args) 
{
    std::common_type_t<Ts...> arr[sizeof...(args)]{ args... };
   
    static_assert(std::is_array_v<int[sizeof...(args)]>, "is not array!");
}

(See a Live Demo)

  • Related