In C you can do int a[] = {1,2,3,4,5}
, but C++11 std::array<int> a = {1,2,3,4,5}
will give a "too few template parameters" compile error. Any way around this?
Asked
Active
Viewed 276 times
2 Answers
5
The best you can have is a make_array
, something like:
template<typename T, typename...Ts>
constexpr std::array<T, 1 + sizeof...(Ts)> make_array(T&& head, Ts&&...tail)
{
return {{ std::forward<T>(head), std::forward<Ts>(tail)... }};
}

Jarod42
- 203,559
- 14
- 181
- 302
-
Why is it `1 + sizeof...(Ts)`? What is the extra space for? – David G Feb 27 '14 at 16:37
-
@0x499602D2: `1` is for the first parameter `T head` (we deduce the type from the `head`). – Jarod42 Feb 27 '14 at 16:45
-3
Implementation of std::array:
template<typename T, std::size_t N>
struct array {
T array_impl[N];
};
So this Should work:
std::array<std::int, 5> a = {{ 1, 2, 3, 4, 5 }};
which is essentially just like (as the compiler agreed to drop off the inner curly brackets.
std::array<std::int, 5> a = { 1, 2, 3, 4, 5 };
See

juanchopanza
- 223,364
- 34
- 402
- 480

Dory Zidon
- 10,497
- 2
- 25
- 39
-
1So how can you do that without saying that the length of the array is 5? – HelloWorld123456789 Feb 27 '14 at 15:54
-
you do specify the array Rikayan, look at the second template parameter that's passed to the template.. – Dory Zidon Feb 27 '14 at 15:55
-
6