How it possible to use operator<<
to push string
s 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:
- When should I prefer non-member non-friend functions to member functions?
You need to use std::vector.push_back() or std::vector.insert() to insert elements inside a vector.
Following piece of code appends to stream. similary you can add it to vector also.
class CustomAddFeature
{
std::ostringstream m_strm;
public:
template <class T>
CustomAddFeature &operator<<(const T &v)
{
m_strm << v;
return *this;
}
};
as it is template
so you can use it for other types also.
// C++11
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string>& operator << (vector<string>& op, string s) {
op.push_back(move(s));
return op;
}
int main(int argc, char** argv) {
vector<string> v;
v << "one";
v << "two";
v << "three" << "four";
for (string& s : v) {
cout << s << "\n";
}
}