Default parameter using another parameter

淺唱寂寞╮ 提交于 2020-01-15 05:50:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!