2

In C++ I want to return a struct by value which contains a variant with an array inside. The struct has no explicit constructors. Is this not possible?

In the following I get the compiler error (gcc):

"error: use of deleted function 'TestStruct2::TestStruct2(const TestStruct2&)'"

It works, if I define constructors. I don't want constructors here.

struct TestStruct2
{
    std::variant<int[5], float[4]> t;
};

TestStruct2 test2()
{
    TestStruct2 t;
    return t;
}

Ernie Mur
  • 481
  • 3
  • 18
  • 16
    Replace your arrays with `std::array`. Problem solved. – Sam Varshavchik Jul 27 '22 at 14:05
  • 4
    raw arrays are not copyable. – NathanOliver Jul 27 '22 at 14:06
  • 2
    I didn't expect `std::variant` to work with raw arrays at all. – HolyBlackCat Jul 27 '22 at 14:07
  • Nathan: Is this also true for copiing the struct? There is no compilation error if I place raw arrays inside the struct without the variant. – Ernie Mur Jul 27 '22 at 14:11
  • 3
    @ErnieMur As a member of a struct or class the array will be copied for you by the default copy constructor. Outside of that, you cannot copy an array. `variant` checks if the types it contains are copyable and since an array by itself is not, it makes the variant non-copyable. – NathanOliver Jul 27 '22 at 14:14
  • @NathanOliver So it would also work to wrap the array into an additional struct? – Ernie Mur Jul 27 '22 at 14:16
  • 2
    @ErnieMur Yes, but there is no need to do that yourself. Just use `std::array` which does this for you. – NathanOliver Jul 27 '22 at 14:17
  • 2
    "So it would also work to wrap the array into an additional struct?" Yes. That's exactly what `std::array` does. – Igor Tandetnik Jul 27 '22 at 14:17
  • 1
    My compiler says `error: static_assert failed due to requirement 'integral_constant::value' "variant can not have an array type as an alternative."` ... which jibes with HolyBlackCat's comment. – Eljay Jul 27 '22 at 14:21

0 Answers0