Assume the following code snippet:
#include <optional>
struct MyStruct
{
// MyStruct(int a) : a(a) {}
int a;
};
int main()
{
std::optional<MyStruct> ms1 = std::make_optional<MyStruct>(1);
std::optional<MyStruct> ms2{2};
std::optional<MyStruct> ms3;
ms3.emplace(3);
std::optional<MyStruct> ms4(std::in_place, 4);
}
This works as intended using c++20 with gcc 11.2, all of those four creation methods fail compilation on clang (Compiler explorer link)
To make it work with clang, I need to uncomment the constructor.
My main question is: Which compiler is correct, clang or gcc?
Follow-up question: If clang is correct, is there any way to create a struct without constructor in an optional, without copying the struct into it, e.g. std::optional<MyStruct> ms{MyStruct{3}}
?
MyStruct(42)
Demo. – Consumerism(..)
instead of{..}
. And internally std containers (asstd::optional
) use()
(and not{}
) to construct user-object. – Consumerismstd::vector
,std::map
, ...std::optional
would do something likenew (&buffer) MyStruct(args...)
. So main issue is thatMyStruct(42)
is a C++20 feature, not yet implemented by Clang.std::optional
didn't change in that regards. – Consumerism