How to return an aggregate initializer as templated struct?

Viewed 50

I want to return an aggregate initializer when the return value is templated:

Msg {
  std::string msgId;
  std::string data; 
};

template <typename T> 
struct RetVal {
  int code;
  std::optional<T> msg;
};
 
RetVal<Msg> fn1() {
  Msg msg{.msgId = "123", .data = "my data"}; // C99 Designator initialization

  return { 200, msg };
}

RetVal<Msg> fn2() {
  Msg msg{.msgId = "456", .data = "my other data"}; // C99 Designator initialization

  return { 200, msg };
}

the MSVC compiler outputs:

'return': cannot convert from 'initializer list' to RetVal MSVC(C2440)

by the way... can I return with some of the fields undefined? like the following:

example 1:

return {, resp};

example 2:

return {code, };

is it possible?

My compiler is the latest MSVC 19.27.

1 Answers

Your code is valid in c++20, and should be compiled by a conformant compiler.


Yes, you can return a Retval<Msg> with some of the fields missing, like this:

return { .code = 200 };
// or  
return { .msg = msg };

Here's a demo that compiles with /std:c++latest.

Related