我们在c ++ 17中有自动数组吗?

时间:2018-06-13 15:23:06

标签: c++ c++17

请考虑以下代码:

auto numbers = {1, 2, 3, 4};    // 'numbers' is an std::intializer_list<int>
auto num_array[] = {1, 2, 3, 4} // error -> declared as an array of 'auto'

为什么会出现这种限制?

3 个答案:

答案 0 :(得分:11)

使用C ++ 17和class template argument deduction,这很好用:

#include <array>
std::array arr{1, 2, 3, 4};
int i = arr.size();  // 4

答案 1 :(得分:3)

询问why语言功能是一个众所周知的难以回答的问题。

但希望有用的版本是:auto是一个非常简单的语言功能,它只是完全扣除,而不是约束演绎。您可以添加一些声明符,例如auto&auto*,但不是全部。原样,它非常有用。只是......并非所有强大的。从一个简单的,受限制的功能集开始,然后随着我们获得经验后再扩展,它通常很有用。

使用Concepts,可能会在声明中添加更多功能以执行更多类型的操作,例如:

std::vector<int> foo();
std::vector<auto> v = foo();

拥有auto数组似乎适合这种模式。绝对不是在C ++ 17中,但可能在C ++ 20中。

答案 2 :(得分:0)

很难看,但可以从原始数组列表初始化程序中推断出元素类型并直接声明数组,如下所示:

template<typename T>
struct array_trait
{
    using element_type = T;
    array_trait(T(&&)[]);
};

decltype(array_trait({4,5,7}))::element_type a[] = {4,5,7};