Вопрос

void foo(Type1 a, Type2 b = value2)

May I know what are the restrictions of Type2 to be a parameter that accepts default value? I reckon value2 of type2 should be decidable at compile time. For example, an integer. Is this correct?

Это было полезно?

Решение

You have quite a lot of flexibility. value2 needs to be an expression which is valid at the point of declaration of the function (by "valid" I mean that the names it uses are in scope, etc), and its type must be implicitly convertible to Type2, same as for any initializer. value2 is evaluated each time the function is called. So for example:

#include <vector>
#include <iostream>

int i;

void foo(std::vector<int> v = std::vector<int>(i)) {
    std::cout << v.size() << "\n";
}

int main() {
    i = 1;
    foo();
    i = 2;
    foo();
}

With the right initializer, Type2 can even be a reference type:

void bar(int &j = i);

Другие советы

value2 must be compile-time convertible to Type2.

Yes correct.

The only limitation is defaulted variable should be last one. You can have multiple default variables just make sure keep them all at the end. Don't mix with non default ones.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top