[英]Is there a simple way to call a function with default arguments?
這是一個帶有默認參數的函數聲明:
void func(int a = 1,int b = 1,...,int x = 1)
當我只想設置x
參數時func(1,1,...,2)
如何避免調用func(1,1,...,2)
,而使用以前的默認參數設置其余參數?
例如,就像func(paramx = 2, others = default)
你不能把它作為自然語言的一部分。 C ++只允許您默認任何剩余的參數,並且它不支持調用站點的命名參數 (參見Pascal和VBA)。
另一種方法是提供一套重載函數。
另外,你可以使用可變參數模板自己設計一些東西。
芭絲謝芭已經提到了你不能這樣做的原因。
問題的一個解決方案是將所有參數打包到struct
或std::tuple
(在這里使用struct
會更直觀)並僅更改您想要的值。 (如果你被允許這樣做)
以下是示例代碼:
#include <iostream>
struct IntSet
{
int a = 1; // set default values here
int b = 1;
int x = 1;
};
void func(const IntSet& all_in_one)
{
// code, for instance
std::cout << all_in_one.a << " " << all_in_one.b << " " << all_in_one.x << std::endl;
}
int main()
{
IntSet abx;
func(abx); // now you have all default values from the struct initialization
abx.x = 2;
func(abx); // now you have x = 2, but all other has default values
return 0;
}
輸出:
1 1 1
1 1 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.