其他分享
首页 > 其他分享> > c – 模板化封闭的模板化结构的初始化列表

c – 模板化封闭的模板化结构的初始化列表

作者:互联网

#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行上,不知道如何解决它.任何帮助或提示将不胜感激,谢谢.

编辑

gcc版本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

问题在于struct initialization = {0}和emplace_back.

解决方法:

emplace_back()使用模板参数推导来确定传递给函数的元素的类型.括号括起初始化列表不是表达式,也没有类型,因此模板无法推断.你必须在这里显式调用构造函数:

items.emplace_back(item_t<3>{{1,2,3}});

标签:list-initialization,c,c11,templates,struct
来源: https://codeday.me/bug/20190728/1562074.html