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
CodePudding user response:
Write a function:
Something createSomething(int v) {
return {v,v,v,v};
}
PS: I suppose the constructor is actually public not private.
CodePudding user response:
class SomethingElse : public Something{
public:
using Something::Something;
SomethingElse (int a)
: Something{a, a, a, a}
{}
};
CodePudding user response:
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);
}
CodePudding user response:
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