语法糖将可变大小的元素列表添加到向量中?

Fra*_*ank 1 c++ vector syntactic-sugar

我有一个包含向量的类:

class Foo {
  typdef std::vector<int> Vec;
  Vec m_kids;
  void addKids(Vec::const_iterator begin, 
               Vec::const_iterator end) {
    m_kids.insert(m_kids.end(), begin, end);
  }
};
Run Code Online (Sandbox Code Playgroud)

有没有办法允许以下简洁的函数调用?(也许通过改变addKids上面的功能?)

int main() {
  Foo foo;
  foo.addKids(23,51,681);             // these...
  foo.addKids(3,6,1,4,88,2,4,-2,101); // ...would be nice?!
}
Run Code Online (Sandbox Code Playgroud)

我怀疑你可以使用C++ 0x向量初始化列表吗?但不幸的是,我无法使用C++ 0x.不过,如果有帮助,我可以使用Boost.

Naw*_*waz 5

你可以这样做:

Foo foo;
foo << 3, 6, 1, 4, 88, 2, 4, -2, 101; //inserts all!
Run Code Online (Sandbox Code Playgroud)

为此,你需要重载<<,运营商,如:

class Foo {
  typdef std::vector<int> Vec;
  Vec m_kids;
public:
  Foo& operator<<(int item) {
    m_kids.push_back(item); return *this;
  }
  Foo& operator,(int item) {
    m_kids.push_back(item); return *this;
  }
};
Run Code Online (Sandbox Code Playgroud)

一旦实现了这个,那么你也可以写:

foo << 3 << 6 << 1 << 4 << 88 << 2 << 4 << -2 << 101; //inserts all!
Run Code Online (Sandbox Code Playgroud)

即使这样,

foo, 3, 6, 1, 4, 88, 2, 4, -2, 101; //inserts all!
Run Code Online (Sandbox Code Playgroud)

或者将两者混合为:

foo << 3, 6, 1 << 4, 88, 2 << 4 << -2, 101; //inserts all!

//and this too!
foo,3 << 6, 1 << 4, 88, 2 << 4 << -2, 101; //inserts all!
Run Code Online (Sandbox Code Playgroud)

一切都一样!

但混合看起来不太好.我的偏好是第一个!