首页 > 解决方案 > 容器有重新绑定吗?

问题描述

在 C++ 标准库allocators中可以反弹。

std::allocator<int>::rebind<double>::otherstd::allocator<double>.

有没有一种简单的方法可以用容器做到这一点?

原因是我有一个将容器元素乘以标量的函数。

template<class Container, typename S>
auto elementwise_multiply_by_scalar(Container const& c, S s){
    Container ret(c.size());
    for(auto& e : ret) e *= s;
    return ret;
}

但如果e * s与 不是同一类型e,我想这样做:

template<class Container, typename S>
auto elementwise_multiply_by_scalar(Container const& c, S s){
    Container::rebind<decltype(Container::value_type{}*s)> ret(c.size());
    auto it2 = ret.begin();
    for(auto it1 = c.begin(); it1 != c.end(); ++it1, ++it2) *it2 = s * *it1;
    return ret;
}

(我想不清楚为什么我希望输出与输入是同一类容器,但我想这是预期的结果。)

我可以使用模板模板参数(如template<template<typename> class V>),但它似乎也有问题。

我们需要某种东西container_traits<V>::rebind吗?(例如container_traits<std::vector<double, myallocator<double> >>::rebind<int>::other-> std::vector<int, myallocator<double>::rebind<int>::other>

标签: c++containerstypetraits

解决方案


像这样的东西可能会起作用:

struct A
{
};

struct B
{
};

struct C
{
};

C operator *(const A&, const B&)
{
    return C();
}

template <typename Container, typename ValueType>
struct ContainerConverter
{
};

template <typename SourceValueType, typename ValueType>
struct ContainerConverter<std::vector<SourceValueType>, ValueType>
{
    typedef typename std::vector<ValueType> result_type;
};

template <typename Container, typename S>
auto mult(const Container& c, const S& s)
{
    typedef typename Container::value_type source_element;
    typedef decltype(c.front()*s) result_element;
    typename ContainerConverter<Container, result_element>::result_type result;
    std::transform(c.begin(), c.end(), std::back_inserter(result), [&](const source_element& e){ return e * s; } );
    return result;
}

int main()
{
    std::vector<A> a;
    std::vector<C> c = mult(a, B());
}

您需要专门ContainerConverter针对要支持的每种容器类型。

如果您的容器不全部支持,std::back_inserter请参阅std::transform to absolute container


推荐阅读