Default parameter using another parameter

The following code is invalid in C ++

struct Test { int x; int y; }; void function(Test A, int n = Ax) { ... } 

because the Ax parameter defaults to A. Is there a way around this limitation? The reason I want to do this is as follows. I have a Vector class that is very close to std :: vector but has a allocator_ member that is responsible for allocating memory. My copy constructor has two options:

 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 the dispenser to be A.allocator_, so I tried

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

Unfortunately, it is not valid C ++. Do any of you have a solution to this problem?

+2
c ++ default-value
source share
2 answers

The simplest solution would be to use overloading instead of the default arguments:

 void function(Test A, int n) { ... } void function(Test A) { function(A, Ax); } 
+8
source share

How about something like that? You can simply use the default value, void (Test A, int n = 0) {n = Ax;
...}

0
source share

All Articles