2012-02-04 34 views
0

我是新來的,現在確定這是否可行。我想將一個參數std::set<std::string>添加到函數中,並將其默認值設置爲NULL,以避免對以前的使用產生影響。我可以使用std :: set <std::string>作爲函數的默認參數嗎?

所以基本上,

func(int a); turns into 
func(int a, std::set<std::string> & temp = NULL); 

但是這會給我一個錯誤"error C2440: 'default argument' : cannot convert from 'int' to 'std::set<_Kty> &'"

任何人可以幫助我在這?

感謝

+0

我不知道,你可以有'NULL'參考。 (而不是指針) – millimoose 2012-02-04 01:17:43

回答

5

爲默認值設置爲NULL,你就必須要路過一個std::set<std::string>*,而不是一個參考值類型。

此外,如果您是通過非指針類型,要不惜一切分配任何默認值,它必須是一個const參考,因爲你不能(適宜地!)分配一個臨時給它除此以外。

所以你的 「默認」 值的選擇基本上:

std::set<std::string>* = NULL 

或:

const std::set<std::string>& = std::set<std::string>() 

或選項3,使用函數重載更直接:

void myfunction() {dothing(0);} 
void myfunction(std::set<std::string>& optional_param) 
{ dothing(optional_param.size()); } 

或選項4,具有相應的bool,指示參數是否爲「設置」:

void myfunction(std::set<std::string>& param, bool param_has_meaning=true) {} 

它看起來像你已經在軌道上的第三個選項。你只需要編寫兩個定義,一個定義和一個沒有參數。

+0

「它必須是一個」const引用「:標準是否指定了這個? – krlmlr 2012-02-04 01:50:51

+1

@ user946850-是的,因爲左值引用無法綁定到臨時對象,因爲它們不是左值。 – templatetypedef 2012-02-04 02:06:09

0

下面會給你一個空set對象:

std::set<std::string>() 
+0

謝謝,我在原型和定義中都改了它,但是現在定義行會給我_「錯誤C2572:***重新定義默認參數:」_ – Derek 2012-02-04 01:21:42

+1

不使用它在定義中,只有在原型 – krlmlr 2012-02-04 01:25:02

+0

明白了,謝謝! – Derek 2012-02-04 01:44:18

1

您不能在C++中使用NULL參考

最簡單的方法是將有一個虛擬的空set

std::set<std::string> empty; 
void func(int a, std::set<std::string>& temp = empty) 
{ 
    // ... 
} 

然後,您可以撥打:

func(1); 

整潔,仍然,是使用重載函數創建一個包裝等等你沒有必要默認:

void func(int a, std::set<std::string>& temp) 
{ 
} 

void func(int a) 
{ 
    std::set<std::string> empty; 
    func(a, empty); 
} 

    // And then... 
    func(1); 

所有這一切都假設我如果你通過set,你會以某種方式修改它。從你的問題中不清楚你的意圖是什麼,但我已經根據你的參考是非const作出了假設。如果我錯算了,那麼答案更簡單:

void func(int a, const std::set<std::string>& temp = std::set<std::string>()) 
{ 
} 
+1

+1也值得一提的是,你可以使用默認參數與常量集。 'void func(int a,std :: set const&temp = std :: set ())' – 2012-02-04 01:40:44

+0

Thanks @LokiAstari。我已經在你的評論後加強了我的回答。 – Johnsyweb 2012-02-04 01:46:48

+1

如果你打算修改'temp',那麼'std :: set &temp = empty'可能不是一個好主意。你可以修改'empty'(通過'temp'),這會使'empty'不再是空的。此外,對'空'的任何修改都不是線程安全的。 – Mankarse 2012-02-04 02:51:16

1

你有正確的想法 - 使用參考。但是,默認情況下,引用不能爲NULL,就像指針一樣。因此,你可能想要做的就是讓你使用void func(int a)當你不希望傳遞一組作爲參數,並使用void func(int a, std::set<std::string>& temp)

這樣,你實際上可以提供兩個不同的實現重載函數 - 一個在一個集合上工作,一個不在。從使用的角度來看,它與默認參數具有相同的效果。從編碼的角度來看,每個實現都有更明確的目的。

如果你不打算要修改設置,我可能會建議使用const引用來代替:

void func(int a, const std::set<std::string>& temp) 
相關問題