Is it possible to use operator<< to push strings into a vector. I searched a lot but only find stream examples.
class CStringData
{
vector< string > myData;
// ...
// inline operator << ... ???
};
I want this to use as a simple elipsis (like void AddData(...) ) exchange for
robust parameters.
CStringData abc;
abc << "Hello" << "World";
Is this possible at all ?
You can define operator<< as:
class CStringData
{
vector< string > myData;
public:
CStringData & operator<<(std::string const &s)
{
myData.push_back(s);
return *this;
}
};
Now you can write this:
CStringData abc;
abc << "Hello" << "World"; //both string went to myData!
But instead of making it member function, I would suggest you to make it friend of CStringData:
class CStringData
{
vector< string > myData;
public:
friend CStringData & operator<<(CStringData &wrapper, std::string const &s);
};
//definition!
CStringData & operator<<(CStringData &wrapper, std::string const &s)
{
wrapper.myData.push_back(s);
return wrapper;
}
The usage will be same as before!
To explore why should you prefer making it friend and what are the rules, read this:
You need to use std::vector.push_back() or std::vector.insert() to insert elements inside a vector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With