简体   繁体   中英

C++ - How to "Fill" a function call and use a default values for arguments

Let's say a third party library exposes a class. Its constructor has no default arguments and all arguments are of the same type.

class Something{
  public: 
    Something(int a, int b, int c, int d);
}; 

Is there any syntax that would allow to instanciate that class with the same default value for each arguments ?

eg :

Something s( sugar_stuff(42) ...) ; // <-> Something s(42,42,42,42);

Thanks, Steven

Write a function:

Something createSomething(int v) { 
    return {v,v,v,v};
}

PS: I suppose the constructor is actually public not private.

class SomethingElse : public Something{
public:
    using Something::Something;
    SomethingElse (int a)
    : Something{a, a, a, a}
    {}
}; 

You can try to create a new function that calls the original function:

void Something_new(int a = 42, int b = 42, int c = 42, int d = 42){
Something(a,b,c,d);
}
 

My favorite is

class Something {
    int a = 0, b = a, c = b, d = c;
}

Something x0{};
Something x1{1};
Something x2{1, 2};
Something x3{1, 2, 3};
Something x4{1, 2, 3, 4};

You can also initialize everything to a or 0 instead of the previous member if you prefer that.


https://godbolt.org/z/Yxj883zsr

x4:
        .long   1
        .long   2
        .long   3
        .long   4
x3:
        .long   1
        .long   2
        .long   3
        .long   3
x2:
        .long   1
        .long   2
        .long   2
        .long   2
x1:
        .long   1
        .long   1
        .long   1
        .long   1
x0:
        .zero   16

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM