用括号括起来的模板化结构的初始化列表 [英] Brace-enclosed initializer list of templated struct
问题描述
#include <array>
#include <vector>
#include <cinttypes>
#include <iostream>
using namespace std;
template<size_t N>
struct item_t {
array<uint32_t, N> weight = {0};
};
int main(void) {
vector<item_t<3>> items;
items.emplace_back({{9,2,3}});
cout << items[0].weight[0] << endl;
return 0;
};
我在这里有点茫然.错误在emplace_back线上,不知道如何解决.任何帮助或提示,将不胜感激,谢谢.
I'm at a bit of a loss here. Error is on the emplace_back line and no idea how to resolve it. Any help or hints would be appreciated, thanks.
编辑
gcc版本4.8.2
gcc version 4.8.2
$ g++ -std=c++11 test.cpp
test.cpp: In function ‘int main()’:
test.cpp:16:30: error: no matching function for call to ‘std::vector<item_t<3ul> >::emplace_back(<brace-enclosed initializer list>)’
items.emplace_back({{9,2,3}});
^
test.cpp:16:30: note: candidate is:
In file included from /usr/include/c++/4.8/vector:69:0,
from test.cpp:2:
/usr/include/c++/4.8/bits/vector.tcc:91:7: note: void std::vector<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = {}; _Tp = item_t<3ul>; _Alloc = std::allocator<item_t<3ul> >]
vector<_Tp, _Alloc>::
^
/usr/include/c++/4.8/bits/vector.tcc:91:7: note: candidate expects 0 arguments, 1 provided
问题在于结构初始化= {0}
和emplace_back
.
The problem is with the struct initialization = {0}
and with emplace_back
.
推荐答案
emplace_back()
使用模板参数推导确定传递给函数的元素的类型.大括号括起来的初始化器列表不是表达式,并且没有类型,因此不能由模板推导.您必须在此处显式调用构造函数:
emplace_back()
uses template argument deduction to determine the types of the elements passed to the function. A brace enclosed initializer list is not an expression and doesn't have type and therefore cannot be deduced by the template. You have to explicitly call the constructor here:
items.emplace_back(item_t<3>{{1,2,3}});
这篇关于用括号括起来的模板化结构的初始化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!