2017-04-23 58 views
0

我試圖解決一個大學問題,除其他外,要求我們編寫一個函數,它需要一個參數:Type1容器,其中包含容器其中包含Type3的容器,其中包含任意類型的元素。容器類型不一定是不同的,但所有已知的是它們僅支持一些函數(例如size()),並且所有維度都是相同的。我們目前只處理了序列容器,所以我認爲他們會用自定義序列容器來測試它。C++ 11:函數模板返回任意類型的2D容器

我需要的是一個返回包含Type1容器的Type2容器的函數。我試圖使用這樣的結構:

template <typename Cube> 
    auto foo(const Cube &bar) -> remove_reference<decltype(bar)> 
    { 
     auto square(remove_reference<decltype(bar)> {}); 
     cout << square.size(); // Throws an error 
     return square; 
    } 

希望decltype可以幫助我製作一個Type2容器,它包含Type1容器。然而,當我調用函數與3D矢量作爲參數:

int main() { 
    vector<vector<vector<int>>> v {{{1}}}; 
    foo(v); 
} 

它拋出一個錯誤:

error: no member named 'size' in 'std::remove_reference<const std::vector<std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >, std::allocator<std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > > > &>' 
       cout << square.size(); 
         ~~~~~~^ 
note: in instantiation of function template specialization 'foo<std::vector<std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >, std::allocator<std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > > > > >' requested here 
    foo(v); 
    ^

我的C++類型的知識差,所以我真的不明白是什麼類型在這裏是「推導出來的」。我們沒有涉及decltype和函數模板的基礎知識,也沒有涉及到可以幫助我們想到的其他內容。我們不允許在我們的課程之外使用這麼多(僅限C++ 11),所以我認爲我要麼在某個地方犯了一個菜鳥錯誤,要麼有一種更優雅的方式來做這件事。

編輯:返回值和方應被指定爲

auto square(remove_reference<decltype(bar[0])> {}); 

回答

0

remove_reference<decltype(bar)>不是從decltype(bar)取出參考 - 你需要

typename remove_reference<decltype(bar)>::type 

閱讀remove_reference documentation