问题
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?
回答1:
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);
}
回答2:
How about something like that?
You can just use default value,
void function(Test A, int n = 0)
{
n=A.x;
...
}
来源:https://stackoverflow.com/questions/28244884/default-parameter-using-another-parameter