Default parameters: can only the last argument(s) be left?

牧云@^-^@ 提交于 2021-01-13 07:55:35

问题


I know it's possible to do something like :

int foo(int a = 0, int b = 1) { return a + b; }

and then use it without the default parameters eg.:

foo();    // a = 0, b = 1 -> 1

or with the last one as default eg.:

foo(2);    // a = 2 and b = 1 default -> 3

But my question is: Is it possible to use the default value for the first argument (a) and give the value of the second (b)

My first thought was doing it like (which doesn't work!):

foo(,2);    // a = 0 default and b = 2

Does a syntax for this exist or is this just not possible ?


回答1:


No, it is not possible in current syntax.




回答2:


Alternatively from specifying default parameter values you can use multiple function overloads like:

 int foo(int a, int b){return a+b; }
 int foo(int b){return foo(0,b); }     
 int foo(){return foo(0,1); }



回答3:


I know that it is not really an answer to your question, but you could try to use boost named parameters. It might be useful for your use case.




回答4:


It is not possible directly. However, it is possible somehow if you declare a struct for the input parameters that encapsulates the default values and has individual setters:

#include <iostream>

struct Foo{
    int a,b;
    Foo() : a(0),b(1) {};
    Foo setA(int x) { a=x; return *this;}
    Foo setB(int x) { b=x; return *this;}
};

void foo(Foo f = Foo()){ std::cout << f.a << "  " << f.b << std::endl; }

int main() {
    foo();                // uses default values for a and b
    foo(Foo().setA(3));   // uses default value for b
    foo(Foo().setB(5));   // uses default value for a
}

This is of course quite some overhead. On the other hand, imho it anyhow makes sense quite often to encapsulate parameters into a struct and provide default values there instead of on the function declaration.




回答5:


Once we provide a default value for a parameter, all subsequent parameters must also have default values. For example,

// Invalid
void add(int a, int b = 3, int c, int d);

// Invalid
void add(int a, int b = 3, int c, int d = 4);

// Valid
void add(int a, int c, int b = 3, int d = 4);


来源:https://stackoverflow.com/questions/39838204/default-parameters-can-only-the-last-arguments-be-left

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!