首先阅读Boost源码剖析之:容器赋值-assign
咋一看这段代码,
| std::vector<int> i_v; i_v += 1, 2, 3, 4, 5; |
首先i_v+=1, 这段要实现就必须重载+=操作符号。实现的代码大概是这样的。
| template<class V, class A, class V2> void operator+=(std::vector<V,A>& c, V2 v) { return c.push_back(v); } |
接下来是解决输入2的问题。 如果上一步的操作返回为空,就不行了,这样的话就连接不起来了。如果返回std::vector对象呢,则中间缺少操作符。所以要对上面的重载操作做一些手术,人工添加个()重载操作,这样就多一层函数的嵌套。
| template<class V, class A, class V2> void operator+=(std::vector<V,A>& c, V2 v) { return push_back(c)(v); } push_back返回的类具有()重载操作,可以这样实现: class class_has_optemplate< class C > { operator()(V2 v) { this.push_back(v); } } |
| // assignment.cpp : Defines the entry point for the console application. // // #define ASSIGN_LIB #include "stdafx.h" #include <vector> #include <map> #include <string> using namespace std; #ifdef ASSIGN_LIB #include "boost/assign/std/vector.hpp" #include "boost/assign/list_inserter.hpp" using namespace boost::assign; #endif #ifndef ASSIGN_LIB template<typename C1> class list_inserter { public: C1& c_; list_inserter(C1& c) : c_(c) { } template<class T> void operator()(T r)//这里存在问题,连接不上!!没有返回list_inserter对象 { c_.push_back(r); } }; template<class C1> list_inserter<C1> make_list_inserter(C1 &c) { return list_inserter<C1>(c); } template <typename C > list_inserter<C> push_back(C& c) { return make_list_inserter(c); } template <typename V, typename A, typename V2> list_inserter<std::vector<V, A>> operator+=(std::vector<V, A>&c, V2 a) { return push_back(c)(a); } #endif int _tmain(int argc, _TCHAR* argv[]) { std::vector<int> i_v; i_v += 2; #ifdef ASSIGN_LIB i_v += 1, 2, 3, 4, 5; printf("%d", i_v.size()); map<string, int> months; insert(months) ("January", 31)("February", 28); #endif return 0; } |
| 为完整解决上面的问题,list_inserter还需要实现逗号的重载类和一个封装好的FUNCTION函数,该函数的功能是计算结果,然后有list_inserter返回本身的对象。 |
