簡體   English   中英

模板封閉的模板化結構的初始化列表

[英]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行上,不知道如何解決它。 任何幫助或提示將不勝感激,謝謝。

編輯

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}});

這里有兩個問題:

嘗試初始化類型為T的對象,就像這個T{...}一樣,稱為聚合初始化 在某些情況下,即使您沒有接受initializer_list的構造函數,也會為其指定默認行為。 C++11 ,不允許提供非默認構造函數或類內初始值設定項。 所以,鑒於這個定義

template<size_t N>                                                              
struct item_t {                                                                 
  array<uint32_t, N> weight   = {0};                                            
};

你不能寫item_t<3> t{1,2,3};

但是,這不是你的問題。 您的代碼失敗的原因是emplace_back嘗試將參數轉發給vector s底層類型的構造函數。 在你的情況下,沒有匹配。 請注意,在此上下文中,braced-init列表不等同於initializer_list ,您無法通過添加initializer_list構造函數來解決此問題,並且必須以其他方式幫助編譯器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM