相关疑难解决方法(0)

如何使用initializer_list初始化成员数组?

我正在快速使用C++ 0x,并使用g ++ 4.6进行测试

我只是尝试了下面的代码,认为它会工作,但它不会编译.我收到错误:

incompatible types in assignment of ‘std::initializer_list<const int>’ to ‘const int [2]’

struct Foo
  {
    int const data[2];

    Foo(std::initializer_list<int const>& ini)
    : data(ini)
    {}
  };

Foo f = {1,3};
Run Code Online (Sandbox Code Playgroud)

c++ arrays initializer-list c++11

50
推荐指数
4
解决办法
3万
查看次数

为什么在模板函数中不允许使用 auto 来创建内置数组?

下面的代码无法编译:

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

int main()
{
    CreateArr(1, 2, 3);
}
Run Code Online (Sandbox Code Playgroud)

由于以下错误:

  • 'arr':在直接列表初始化上下文中, for 的类型'auto [6]'只能从单个初始化表达式推导
  • auto [6]':数组的元素类型不能包含'auto'
  • “正在初始化”:无法从 转换'const int''std::initializer_list<int>'

我的问题是:

  • 为什么我不能使用auto来定义数组的类型?

  • 如何正确定义它以与模板一起使用?

c++ templates auto c++11 c++17

3
推荐指数
1
解决办法
290
查看次数

标签 统计

c++ ×2

c++11 ×2

arrays ×1

auto ×1

c++17 ×1

initializer-list ×1

templates ×1