The default arguments must be bound at compile time - why?

Why was C ++ designed like this? ...

(This question is different, but closely related to

Impossible: this pointer as a default argument. Why? )

+4
source share
2 answers

Actually, this is not entirely accurate. Limitations:

8.3.6 Default Arguments [dcl.fct.default]

7) Local variables should not be used in the default argument. [Example:

void f() { int i; extern void g(int x = i); //error // ... } 

-end example]

8) The this should not be used in the default argument for a member function. [Example:

 class A { void f(A* p = this) { } // error }; 

So, this and local variables cannot be used as default values.

For example, the following is valid:

 int a = 1; int f(int); int g(int x = f(a)); // default argument: f(::a) void h() { a = 2; { int a = 3; g(); // g(f(::a)) } } 

g will be called with a value of f(2) , which is not a compile-time constant. This is an example directly from the standard.

Reasons like him are common: either there was no offer for him, or it was rejected, it was considered not necessary or too difficult to implement.

+11
source

By default, arguments are parameter values ​​that should be used in the body of the function. The value of this variable (i.e. the parameter) may be overridden depending on how the function is called. But while not there - the default argument is the value for this variable - and a value must be defined. This value should be dynamic, and not be bound at compile time - then perhaps it is better to use a separate function to calculate this value and does not look like the default arena. Also, for such a scenario, C ++ already has the correct mechanism - Polymorphism by overloading functions.

Consider this: You need to call the function Fn either with the parameter v , or by default it should be Fn(x) here, and v and x are variables.

Instead of going through the default options, this could be easily implemented using function overloading.

 BOOL x; VOID Fn(BOOL v) { ... } VOID Fn() { Fn(::x); } VOID Main() { ::x = ...; // Variable x value is altered Fn(FALSE); Fn(); // Param value defaults to value of x } 

This forces the programmer to write better code, which is likely to be worth that time in a longer mode.

0
source

Source: https://habr.com/ru/post/1439912/


All Articles