Return any type of object from a method

Flaviu_ 791 Reputation points

I have the following code:

struct SResponse
 SResponse(bool state, std::any value) : _state(state), _value(value) {}
 bool        _state = false;
 std::any    _value;

 SResponse GetResponse();

// implementation
SResponse CSomeClass::GetResponse()
 std:string message{"Aloha"};
 SResponse res(true, std::make_any<std::string>(message);

 return res;

Using code:

CSomeClass some;
std::any result = some.GetResponse();
std::string message{};
try { message = std::any_cast<std::string>(result.second); }
catch (...) {}

In fact, I have returned std::any. But I want to replace this with something else. But what ? As you can see, in std::any I can put anything, but what can I use instead of std::any ? Because std::any take pretty much memory at 64bit apps. Beside that, std::any is available only from c++17, and this could not be used on old code.

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,316 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Guido Franzke 2,201 Reputation points

    what is the benefit of this code?
    I suggest you should use templates instead. templates

    Regards, Guido