[英]Initializing std::tuple from initializer list
我想知道元組是否可以通過初始化列表初始化(更准確地說 - 初始化列表的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}} };
我只想實現使用struct而不是tuple的相同功能(因此只有數組由initializer_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}} };
但似乎所有麻煩都在於數組,它沒有初始化器列表的構造函數,並且使用適當的構造函數包裝數組似乎不是那么容易的任務。
初始化列表與元組無關。
我認為你在C ++ 0x中混淆了花括號的兩種不同用法。
initializer_list<T>
是一個同類集合(所有成員必須屬於同一類型,因此與std::tuple
無關) 這是一個簡化版本:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.