2

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?

2
  • What's wrong with a simple Vector(const Vector& A, Allocator& allocator):allocator(A.allocator_){...}? Commented Jan 30, 2015 at 21:28
  • 1
    An overload, perhaps? Commented Jan 30, 2015 at 21:28

2 Answers 2

10

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); } 
Sign up to request clarification or add additional context in comments.

1 Comment

It is so obvious I wonder why I did not think about it. Maybe overloading a copy constructor was against my feelings. But it works. Thanks.
-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.