2013-06-23 114 views
3

我想實現一個容器,它可以通過爲構造函數提供值序列來接受初始元素列表。模板參數推導/替換失敗

9 template <typename C, int max> 
10 struct c_array 
11 { 
12  typedef C value_type; 
13 
14  typedef C* iterator; 
15  typedef const C* const_iterator; 
16 
17  typedef C& reference; 
18  typedef const C& const_reference; 
19 
20  c_array() { } 
21  template <class T> 
22   c_array(typename T::iterator begin,typename T::iterator end) 
23   { 
24   } 
25 
26  C v[max]; 
27  operator C*() { return v; } 
28 
29  reference operator[] (ptrdiff_t i) { return v[i]; } 
30  const_reference operator[] (ptrdiff_t i) const { return v[i]; } 
31 
32  iterator begin() { return v; } 
33  const_iterator begin() const { return v; } 
34 
35  iterator end() { return v+max; } 
36  const_iterator end() const { return v+max; } 
37 
38  size_t size() const { return max; } 
39 }; 
40 
41 int main(int argc, char** argv) 
42 { 
43  std::vector<int> myvector(10,10); 
44  c_array<int,10> myarray1(myvector.begin(),myvector.end()); 
     ... 

我收到以下錯誤,而編譯提前

... 
test.cc:56:61: error: no matching function for call to ‘c_array<int, 10>::c_array(std::vector<int>::iterator, std::vector<int>::iterator)’ 
test.cc:56:61: note: candidates are: 
test.cc:22:9: note: template<class T> c_array::c_array(typename T::iterator, typename T::iterator) 
test.cc:22:9: note: template argument deduction/substitution failed: 
test.cc:56:61: note: couldn't deduce template parameter ‘T’ 
... 

感謝,

回答

6

在聲明

template <class T> 
c_array(typename T::iterator begin,typename T::iterator end) 

T在一個叫做「非方式使用被誘惑的背景「。沒有合理的方法,如果您傳入MyCustomIter類型的參數,編譯器會猜測T可能包含typedef MyCustomIter iterator;。所以C++標準說編譯器甚至不應該嘗試。

相反,您可以編寫函數來採取任何類型並假設/記錄它應該是一個迭代器。

template <class InputIter> 
c_array(InputIter begin, InputIter end) { 
    std::copy_n(begin, max, v); 
} 
+0

+1爲清楚地解釋爲什麼你需要這種改變。一個額外的註釋可能對OP來說可能是新的,對於普通函數來說,如果模板演繹不能成功,它不一定是個問題,只要能夠明確指定模板參數即可。模板構造函數不存在這樣的語法,因此模板參數無法推導出的模板化構造函數永遠不會被調用。 – hvd

+0

+1非常感謝 –