2013-12-09 38 views
4

首先我應該指出這是我的第一個stackoverflow問題,所以請耐心等待。重載的函數歧義

我有一些問題在C++中重載函數。我試圖創建一個函數具有以下原型:

void push_at_command(std::string, std::vector<std::string>, int); 

void push_at_command(std::string, std::vector<std::string>, std::vector<std::string>, int); 

void push_at_command(std::string, std::vector<std::string>, std::vector<std::string>, std::vector<std::string>, int); 

void push_at_command(std::string, std::vector<std::string>, bool, int); 

我本來想過去的過載(具有布爾)接受一個boost ::正則表達式,而不是一個字符串向量;

void push_at_command(std::string, boost::regex, int); 

但跑進歧義錯誤...所以只是快速獲取代碼「工作」我想我會添加一個原型接受一個標誌,並使用第一個元素的載體來存儲一個正則表達式字符串,但我似乎遇到了布爾類似的問題。

這是我正在努力把這些不同的重載:

push_at_command(
    "AT?S", 
    boost::assign::list_of("(\\d{3}.\\d{3})"), 
    true, 
    0); 
push_at_command(
    "AT?S", 
    boost::assign::list_of("L11")("L12"), 
    0); 
push_at_command(
    "AT?S", 
    boost::assign::list_of("L11"), 
    boost::assign::list_of("L21")("L22"), 
    0); 

這是我得到的錯誤:

error: call of overloaded ‘push_at_command(const char [5], boost::assign_detail::generic_list<char [4]>, boost::assign_detail::generic_list<char [4]>, int)’ is ambiguous 
note: candidates are: 
note: void push_at_command(std::string, std::vector<std::basic_string<char> >, std::vector<std::basic_string<char> >, int) 
note: void push_at_command(std::string, std::vector<std::basic_string<char> >, bool, int) 

...這涉及第三個功能呼叫。

只是要注意,我沒有問題之前,我用bool添加重載(或將字符串向量更改爲正則表達式)。

我假設這個問題與我在函數調用中使用boost :: assign有關,我意識到我不需要,但我真的需要'單線'函數調用。 ...任何意見的歡迎,因爲我對C++來說是新手。

感謝

+2

我的個人建議:如果避免語法超載,你的生活會更快樂。 –

+0

感謝您的建議,我想您可能是對的! –

回答

2

的問題是,隨着增壓文檔,But what if we need to initialize a container? This is where list_of() comes into play. With list_of() we can create anonymous lists that automatically converts to any container:

在看到在這種情況下,你不希望能夠轉換爲任何容器,你要明確š載體。既然你有這個可轉換類型,它不能決定它是否應該轉換爲布爾或向量,使呼叫模糊。

如果你真的想要繼續你已經創建的重載集(請退後一步,並重新考慮你的方法使用一個標誌),你需要專門分配一個向量列表(I' M}這裏假設list_of提供了一個轉換操作符向量):

push_at_command(
    "AT?S", 
    boost::assign::list_of("L11"), 
    std::vector<std::string>(boost::assign::list_of("L21")("L22")), 
    0); 
+0

但是如果你只保留使用bool的函數,你會得到 錯誤:從類型'std :: _ Deque_iterator < 。 這表明它不能轉換爲布爾 – yosim

+0

感謝您的建議,我現在重新組織和重新設計我的程序不使用這些重載。 –

2

錯誤消息告訴你的問題是什麼。這是越來越陷入困境的調用是第三個:

push_at_command(
    "AT?S", 
    boost::assign::list_of("L11"), 
    boost::assign::list_of("L21")("L22"), 
    0); 

,問題是,它可以匹配push_at_command第三和第四版本。它們在第三個參數的類型上有所不同:一個採用vector,另一個採用bool

所以問題是boost::assign::list_of("L21")("L22)可以轉換爲vector它可以轉換爲bool,並且規則不喜歡其中一個轉換。在這樣的情況下,你必須幫助編譯器,將static_cast設置爲所需的類型。或者重新思考這些功能的組織結構,並且可能重新排列這些參數,以避免模棱兩可。 (這就是爲什麼,例如std::string的構造函數需要(int, char),並且沒有構造函數用於一個單獨的char,這會導致含糊不清;這是一個尷尬的接口,由過多的重載驅動)。

+0

請看我對Mark B的問題。它也與你的答案有關。 – yosim