+ =在没有提升的载体 [英] += on a vector without boost

查看:157
本文介绍了+ =在没有提升的载体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用了矢量+ =运算符不使用升压或使用衍生化类?

例如:

  somevector + = 1,2,3,4,5,6,7;

实际上是

  somevector.push_back(1);
somevector.push_back(2);
somevector.push_back(3);
等等


解决方案

随着一点点丑操作符重载,这是不是太难以实现。该溶液可以很容易地制成更通用,但它应当作为一个适当的实施例。

 的#include<矢量>

您需要的语法使用两家运营商:在 + = 运营商和运营商。首先,我们需要创建一个包装类,使我们能够运用运营商一个元素推到一个向量的后面:

 模板< typename的T>
结构push_back_wrapper
{
    明确push_back_wrapper(性病::矢量< T>&放大器; 5):v _(&放大器; 5){}    push_back_wrapper&安培;运营商(常量T&安培; X)
    {
        v _->的push_back(X);
        返回*这一点;
    }    的std ::矢量< T> * V_;
};

于是,为了结合 + = 上的向量利用这一点,我们重载 + = 运营商的载体。我们返回 push_back_wrapper 实例,这样我们就可以推链背上用逗号操作:

 模板< typename的T,typename的U>
push_back_wrapper< T>运算符+ =(的std ::矢量< T>&安培; V,const的U&安培; X)
{
    v.push_back(X);
    返回push_back_wrapper< T>(五);
}

现在我们可以写出code,你在你的例子有:

  INT的main()
{
    的std ::矢量<&INT GT;伏;
    V + = 1,2,3,4,5,6,7;
}

V + = 1 将调用我们的运算符+ = 超载,将返回的实例 push_back_wrapper 。然后,逗号运算符应用于每个在随后的元素之列。

Is there any way to use the += operator with a vector without using boost or using a derivated class?

Eg.

somevector += 1, 2, 3, 4, 5, 6, 7;

would actually be

somevector.push_back(1);
somevector.push_back(2);
somevector.push_back(3);
etc.

解决方案

With a little ugly operator overloading, this isn't too difficult to accomplish. This solution could easily be made more generic, but it should serve as an adequate example.

#include <vector>

Your desired syntax uses two operators: the += operator and the , operator. First, we need to create a wrapper class that allows us to apply the , operator to push an element onto the back of a vector:

template <typename T>
struct push_back_wrapper
{
    explicit push_back_wrapper(std::vector<T>& v) : v_(&v) { }

    push_back_wrapper& operator,(const T& x)
    {
        v_->push_back(x);
        return *this;
    }

    std::vector<T>* v_;
};

Then, in order to use this in conjunction with += on a vector, we overload the += operator for a vector. We return a push_back_wrapper instance so that we can chain push backs with the comma operator:

template <typename T, typename U>
push_back_wrapper<T> operator+=(std::vector<T>& v, const U& x)
{
    v.push_back(x);
    return push_back_wrapper<T>(v);
}

Now we can write the code you have in your example:

int main()
{
    std::vector<int> v;
    v += 1, 2, 3, 4, 5, 6, 7;
}

The v += 1 will call our operator+= overload, which will return an instance of the push_back_wrapper. The comma operator is then applied for each of the subsequent elements in the "list."

这篇关于+ =在没有提升的载体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆