短くて汚い方法 (Boost に似ていますlist_of()
)
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
template <typename T>
struct vlist_of : public vector<T> {
vlist_of(const T& t) {
(*this)(t);
}
vlist_of& operator()(const T& t) {
this->push_back(t);
return *this;
}
};
int main() {
const vector<int> v = vlist_of<int>(1)(2)(3)(4)(5);
copy(v.begin(), v.end(), ostream_iterator<int>(cout, "\n"));
}
現在、C++11 には初期化リストがあるため、そのようにする必要はなく、Boost を使用する必要さえありません。ただし、例として、次のように C++11 で上記をより効率的に実行できます。
#include <iostream>
#include <vector>
#include <utility>
#include <ostream>
using namespace std;
template <typename T>
struct vlist_of : public vector<T> {
vlist_of(T&& t) {
(*this)(move(t));
}
vlist_of& operator()(T&& t) {
this->push_back(move(t));
return *this;
}
};
int main() {
const vector<int> v = vlist_of<int>(1)(2)(3)(4)(5);
for (const auto& i: v) {
cout << i << endl;
}
}
operator=(vlist_of&&)
ただし、ベクトルが定義されていないため、C++11 初期化子リストを使用するほど効率的ではありません。
次のように変更された tjohns20 の方法は、より良い c++11 である可能性がありますvlist_of
。
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
template <typename T>
class vlist_of {
public:
vlist_of(T&& r) {
(*this)(move(r));
}
vlist_of& operator()(T&& r) {
v.push_back(move(r));
return *this;
}
vector<T>&& operator()() {
return move(v);
}
private:
vector<T> v;
};
int main() {
const auto v = vlist_of<int>(1)(2)(3)(4)(5)();
for (const auto& i : v) {
cout << i << endl;
}
}