从初始化程序列表初始化std :: tuple

我想知道是否可以通过初始化列表来初始化元组(更确切地说 – initializer_lists的initializer_list)? 考虑元组的定义:

typedef std::tuple< std::array<short, 3>, std::array<float, 2>, std::array<unsigned char, 4>, std::array<unsigned char, 4> > vertex; 

有没有办法做到以下几点:

 static vertex const nullvertex = { {{0, 0, 0}}, {{0.0, 0.0}}, {{0, 0, 0, 0}}, {{0, 0, 0, 0}} }; 

我只是想实现相同的function,我使用结构,而不是元组(因此只有数组initialize_list初始化):

 static struct vertex { std::array<short, 3> m_vertex_coords; std::array<float, 2> m_texture_coords; std::array<unsigned char, 4> m_color_1; std::array<unsigned char, 4> m_color_2; } const nullvertex = { {{0, 0, 0}}, {{0.0, 0.0}}, {{0, 0, 0, 0}}, {{0, 0, 0, 0}} }; 

我没有理由必须使用元组,只是想知道。 我问,因为我无法通过由我尝试这样的元组初始化生成的g ++模板错误。

@Motti:所以我错过了统一初始化的正确语法 –

 static vertex const nullvertex = vertex{ {{0, 0, 0}}, {{0.0, 0.0}}, {{0, 0, 0, 0}}, {{0, 0, 0, 0}} }; 

 static vertex const nullvertex{ {{0, 0, 0}}, {{0.0, 0.0}}, {{0, 0, 0, 0}}, {{0, 0, 0, 0}} }; 

但似乎所有的麻烦在于数组,它没有initializer_list的构造函数,并且用适当的构造函数包装数组似乎不是那么容易的任务。

初始化器列表与元组无关。

我认为你在C ++ 0x中混淆了花括号的两种不同用法。

  1. initializer_list<T>是同类集合(所有成员必须是相同的types,因此与std::tuple不相关)
  2. 统一初始化是用大括号来构造各种对象的地方; 数组,POD和带构造函数的类。 这也有解决最令人头痛的parsing的好处)

这是一个简化的版本:

 std::tuple<int, char> t = { 1, '1' }; // error: converting to 'std::tuple<int, char>' from initializer list would use // explicit constructor 'std::tuple<_T1, _T2>::tuple(_U1&&, _U2&&) // [with _U1 = int, _U2 = char, _T1 = int, _T2 = char]' std::tuple<int, char> t { 1, '1' }; // note no assignment // OK, but not an initializer list, uniform initialization 

错误消息说,你试图隐式调用构造函数,但它是一个显式的构造函数,所以你不能。

基本上你想要做的是这样的:

 struct A { explicit A(int) {} }; A a0 = 3; // Error: conversion from 'int' to non-scalar type 'A' requested A a1 = {3}; // Error: converting to 'const A' from initializer list would use // explicit constructor 'A::A(int)' A a2(3); // OK C++98 style A a3{3}; // OK C++0x Uniform initialization