加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:53:00 所属栏目:百科 来源:网络整理
导读:#include array #include vector #include cinttypes #include iostream using namespace std; templatesize_t N struct item_t { arrayuint32_t,N weight = {0}; }; int main(void) { vectoritem_t3 items; items.emplace_back({{9,2,3}}); cout items[0].w
#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,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,3}});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读