4

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.

DarioP
  • 5,377
  • 1
  • 33
  • 52
  • I don't think there's a way. Maybe someone knows a clever trick, but I doubt it. Reverse direction would be possible: Define a tuple with the default arguments that you want, then use the elements of the tuple as defaults, then you can use those tuple elements to "retrieve" the defaults that were specified using the tuple. – eerorika Jun 09 '20 at 17:14
  • C++ doesn't have reflection yet. – xaxxon Jun 09 '20 at 17:55

1 Answers1

1

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.

Carlos Ch
  • 393
  • 3
  • 11
  • Yeah, I suspected that default arguments are legacy stuff implemented with some trick at the preprocessor level :( – DarioP Jun 09 '20 at 18:12
  • 2
    @DarioP -- default arguments have nothing to do with the preprocessor. And I have no idea what you intend by labeling them "legacy stuff"; they're part of the language, and they are often useful. – Pete Becker Jun 09 '20 at 18:19
  • @PeteBecker of course they are useful. By "legacy" I mean something like macros or c-style casting or typedef: tools being there since the very early days, with a somewhat "hacky" feeling and that somehow survived every attempt at better integrating them in the language. They are often frown upon, yet not deprecated. But this is just my feeling, do not take it too literally ;) – DarioP Jun 10 '20 at 07:58