DarioP
DarioP

Reputation: 5465

Is it possible to get the default value(s) of the argument(s) of a function in C++?

The retrieval of the argument types of a function has been discussed multiple times, for instance here and here.

I would like to take this a step further and, for the arguments that specify a default value, get it as well. More specifically, assuming that all the arguments which do not come with a default value can be default constructed, I would like to get a tuple initialized with the default (specified or otherwise constructed) values.

Any chance of doing this in C++? The latest standard is welcomed.

I would like to keep the usual function declarations, but, since I suspect that this is not feasible, a sleek pattern relying on functors could also be acceptable.

Upvotes: 5

Views: 402

Answers (1)

Carlos Ch
Carlos Ch

Reputation: 403

At the moment there does not seem to be any tool to get this information. The main reason is because of how the compiler preprocesses your source code with the default initializers.

(Using https://cppinsights.io/) The following code:

void test(int a = 4)
{
  std::cout << a << std::endl;
}

int main()
{
  test(10);
  test();
}

Will translate to this for the compiler:

void test(int a)
{
  std::cout.operator<<(a).operator<<(std::endl);
}

int main()
{
  test(10);
  test(4);
}

The information of the default is lost at that moment.

Upvotes: 1

Related Questions