This is much simpler if you use std::array
, i.e. you can use the immediately invoke lambda to return the corresponding array based on the value of sz
// sz can only be 3 or 4
template<int sz>
void func() {
std::array<int, sz> arr = []() -> std::array<int, sz> {
if constexpr (sz == 4)
return {1, 1, 1, 1};
else
return {1, 1, 1};
}();
}
Since C++17 guarantees copy elision, copy/move construction is not involved here.
C++14 solution
std::array<int, 3>
gen_arr(std::integral_constant<int, 3>) {
return {1, 1, 1};
}
std::array<int, 4>
gen_arr(std::integral_constant<int, 4>) {
return {1, 1, 1, 1};
}
// sz can only be 3 or 4
template<int sz>
void func() {
std::array<int, sz> arr = gen_arr(std::integral_constant<int, sz>{});
}