mardi 26 janvier 2016

Constructing std::string using << operator

If we want to construct a complex string, say like this: "I have 10 friends and 20 relations" (where 10 and 20 are values of some variables) we can do it like this:

std::ostringstream os;
os << "I have " << num_of_friends << " friends and " << num_of_relations << " relations";

std::string s = os.str();

But it is a bit too long. If in different methods in your code you need to construct compound strings many times you will have to always define an instance of std::ostringstream elsewhere.

Is there a shorter way of doing so just in one line?

I created some extra code for being able to do this:

struct OstringstreamWrapper
{
     std::ostringstream os;
};

std::string ostream2string(std::basic_ostream<char> &b)
{
     std::ostringstream os;
     os << b;
     return os.str();
}

#define CreateString(x) ostream2string(OstringstreamWrapper().os << x)

// Usage:
void foo(int num_of_friends, int num_of_relations)
{
     const std::string s = CreateString("I have " << num_of_friends << " and " << num_of_relations << " relations");
}

But maybe there is simpler way in C++ 11?

Aucun commentaire:

Enregistrer un commentaire