2

I think, there is a common situation, when one function (a) is being called from within another one (b), while 'a' have some default parameters and 'b' is needed to support them. For example:

void a(int v1, int v2=0, int v3=1);
void b(int m1, int m2, int v1, int v2=0, int v3=1) {
    // ...
    a(v1, v2, v3);
    // ...
}

But this is the violation of the DRY principle. It can leads a subtile bug, when default parameter of 'a' was changed, but not changed in 'b':

void a(int v1, int v2, int v3=0);
void b(int m1, int m2, int v1, int v2=0, int v3=1) {
    // ...
    a(v1, v2, v3);
    // ...
}

Why there is no mechanism in C++ to inherit default parameter values? It might look like:

void a(int v1, int v2=0, int v3=1);
void b(int m1, int m2, int v1, int v2=default(a::v2, 0), int v3=default(a::v3, 1)) {
    // ...
    a(v1, v2, v3);
    // ...
}

Whether there are languages, that have such syntax?

It might be an offtopic on this board?

4

2 回答 2

5

问题实际上是幻数的使用。如果你去掉幻数,问题就很好地解决了。

enum DefaultA { DefaultA_v2 = 0, DefaultA_v3 = 1 };

void a(int v1, int v2=DefaultA_v2, int v3=DefaultA_v3);

void b(int m1, int m2, int v1, int v2=DefaultA_v2, int v3=DefaultA_v3) {
    // ...
    a(v1, v2, v3);
    // ...
}
于 2013-08-21T03:34:46.987 回答
0

“但这违反了 DRY 原则。当 'a' 的默认参数被更改,但在 'b' 中没有更改时,它会导致一个细微的错误”

坦率地说,如果你得到这个“错误”,那么你的函数就太紧耦合了。独立功能应该是独立的。如果更改一个函数的默认参数会导致另一个函数中断,我认为你有一个设计问题。

于 2013-08-21T04:25:46.463 回答