22

Some std::optional constructors use an std::in_place_t tag parameter like this:

template< class... Args > 
explicit optional( std::in_place_t, Args&&... args );

I see that such constructors could be implemented without the in-place tag and use some enable_if (SFINAE) magic to not participate as unwilling overloads, i.e.:

template< class... Args > 
explicit optional( Args&&... args );

Why are std::optional’s in-place constructors implemented with an std::in_place_t tag rather than with some enable_if magic (and no tag)?

Update: Question is slightly updated to emphasize that I realize that simply omitting the in-place tag wouldn’t work.

Olivia Stork
  • 4,660
  • 5
  • 27
  • 40
oliora
  • 839
  • 5
  • 12

1 Answers1

22

As Passer By said in the comment, the intent is to disambiguate the situation where one wants to call the default constructor of optional<T> and the situation where one wants to call the default constructor of T.

This intention is proposed in N3527, where the original proposed name of in_place_t is emplace. I quote the related part here:

We need the extra tag to disambiguate certain situations, like calling optional's default constructor and requesting T's default construction:

optional<Big> ob{emplace, "1"}; // calls Big{"1"} in place (no moving)
optional<Big> oc{emplace};      // calls Big{} in place (no moving)
optional<Big> od{};             // creates a disengaged optional
xskxzr
  • 12,442
  • 12
  • 37
  • 77
  • 2
    How do you search for papers/proposals? – David G Apr 11 '18 at 09:58
  • 4
    @0x499602D2 I searched with the keywords "C++ in_place_t paper", and find N3793, then find N3527. – xskxzr Apr 11 '18 at 10:37
  • 2
    @0x499602D2 If you have access to the CppLang Slack, you can message npaperbot. It's really great! – Rakete1111 Apr 11 '18 at 15:12
  • @xskxzr If ```std::optional``` constructor is fed in 2 args or more, can't it then be always assumed that these need to be forwarded to ```T's``` constructor and therefore not require ```in_place_t``` ? – user3882729 Jul 04 '21 at 22:39
  • @user3882729 It would be very odd that the interface for 2 or more args is different from the one for 1 arg. – xskxzr Jul 05 '21 at 01:20