Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default parameter using another parameter

The following code is not valid in C++

struct Test {
    int x;
    int y;
};

void function(Test A, int n = A.x) {
    ...
}

because the default parameter A.x depends upon A. Is there a way to go around this limitation? The reason why I want to do this is the following. I have a class Vector that behaves very closely to std::vector but has a member allocator_ which is responsible for allocating memory. My copy constructor takes 2 parameters:

Vector(const Vector& A, Allocator& allocator) {
    ...
}

Such copy constructors are allowed by the standard if the second parameter has a default value. But I want the default value for allocator to be A.allocator_ which is why I've tried

Vector(const Vector& A, Allocator& allocator = A.allocator_) {
    ...
}

Unfortunately, it is not valid C++. Does any one of you have a solution for this problem?

like image 404
InsideLoop Avatar asked Feb 05 '26 20:02

InsideLoop


1 Answers

The easiest solution would be to use an overload instead of default arguments:

void function(Test A, int n) {
    ...
}

void function(Test A) {
    function(A, A.x);
}
like image 81
Baum mit Augen Avatar answered Feb 07 '26 09:02

Baum mit Augen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!