2012-05-17 52 views
0

如下頭可與當我調用該函數蝙蝠不帶參數如預期中的註釋部分:的默認容器參數

class Test 
{ 
public: 

    void bat(std::vector<int> k = std::vector<int>()) {} 
    //void cat(std::map<int, std::vector<int> > k = std::map<int, std::vector<int> >()) {} 

}; 

但是當我嘗試使用在頭貓功能:

class Test 
{ 
public: 

    void bat(std::vector<int> k = std::vector<int>()) {} 
    void cat(std::map<int, std::vector<int> > k = std::map<int, std::vector<int> >()) {} 

}; 

我得到:

test.h:14: error: expected ',' or '...' before '>' token 
test.h:14: error: wrong number of template arguments (1, should be 4) 
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_map.h:92: error: provided for 'template<class _Key, class _Tp, class _Compare,\ 
class _Alloc> class std::map' 
test.h:14: error: default argument missing for parameter 2 of 'void Test::cat(std::map<int, std::vector<int, std::allocator<int> >, std::less<int>, std::all\ 
ocator<std::pair<const int, std::vector<int, std::allocator<int> > > > >, std::vector<int, std::allocator<int> >)' 

怎麼來的?有沒有簡單的解決方法呢?希望不需要在界面中改變指針類型?

這是我的完整標題:

#ifndef TEST_H 
#define TEST_H 

#include <map> 
#include <vector> 
#include <sstream> 
#include <iostream> 

class Test 
{ 
public: 

    //void bat(std::vector<int> k = std::vector<int>()) {} 
    void cat(std::map<int, std::vector<int> > k = std::map<int, std::vector<int> >()) {} 

}; 


#endif 

因此,所有的權利,包括在那裏。我的海灣合作委員會版本過時了(不在家,在家裏也不行) - 但在工作中它是4.1.2

+2

聞起來像一個GCC的bug - [失敗4.3.4](http://ideone.com/alZRI),[適用於4.5.1](http://ideone.com/6Ppze)。你使用什麼版本? – ildjarn

+0

這個編譯好,你包括''? – AJG85

+0

錯誤信息將指向4.1.2,包含''。 – Mat

回答

4

該代碼看起來不錯,但在gcc 4.3.4上失敗,請參閱here,但在4.6以後版本(我沒有測試4.4或4.5)時編譯正常。所以看起來解決方法是使用新的gcc。

#include <map> 
#include <vector> 

class Test 
{ 
public: 

    void bat(std::vector<int> k = std::vector<int>()) {} 
    void cat(std::map<int, std::vector<int> > k = std::map<int, std::vector<int> > 
()) {} 

}; 

int main() { 

} 

關於默認參數,它可能是一個想法,完全放棄他們:

class Test { 
public: 

    void bat(std::vector<int> k) {} 
    void bat() {} 
    void cat(std::map<int, std::vector<int> > k) {} 
    void cat() {} 
}; 

否則,你的情侶默認參數的接口,這意味着無需重新編譯,你無法改變他們所有客戶端代碼。

+0

真實的情況是我有一個功能,它是否需要最終的容器或不同。重載代碼有相當多的重複代碼,並且非常惱人的維護,但我意識到如果可選的最終容器是空的,它會流暢地通過沒有它的版本,所以我合併了兩個重載和默認的爭論最終容器到一個空的..我認爲一種解決方法可能是提供沒有它的重載,但只是將一個空容器的調用轉發給唯一的實現。 –

+0

@PalaceChan是的,這聽起來像一個合理的解決方案。 – juanchopanza

0

你發佈的代碼看起來很好,所以我打算打開我的心理調試器模塊。

你有沒有:

#include <vector> 

...在你的頭?

+0

是的,我的確看起來越來越像人們正在討論的錯誤。 –

0

從這裏的其他帖子看來,它可能是一個編譯器問題,在這種情況下,您可以通過使用typedef而不是直接使用地圖類型來避開它。

#include <vector> 
#include <map> 

class Test 
{ 
public: 
    typedef std::map<int, std::vector<int> > MyMap; 

    void bat(std::vector<int> k = std::vector<int>()) {} 
    void cat(MyMap k = MyMap()) {} 

}; 

int main() 
{ 
}