默认参数使用另一个参数 [英] Default parameter using another parameter
问题描述
以下代码在C ++中无效
The following code is not valid in C++
struct Test {
int x;
int y;
};
void function(Test A, int n = A.x) {
...
}
因为默认参数Ax取决于A.有办法解决这个限制吗?我想这样做的原因如下。我有一个类Vector,行为非常接近std :: vector但有一个成员allocator_,它负责分配内存。我的拷贝构造函数有两个参数:
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) {
...
}
如果第二个参数具有默认值, 。但我想分配器的默认值是A.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_) {
...
}
不幸的是,它是无效的C ++。您是否有任何一个人有这个问题的解决方案?
Unfortunately, it is not valid C++. Does any one of you have a solution for this problem?
推荐答案
最简单的解决方案是使用重载而不是默认参数:
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);
}
这篇关于默认参数使用另一个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!