简体   繁体   中英

use operator << to push std::strings in a vector

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:

您需要使用std :: vector.push_back()std :: vector.insert()在向量中插入元素。

// 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";
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM