c++ - 容器有重新绑定(bind)吗?

标签 c++ containers typetraits

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

std::allocator<int>::rebind<double>::other给出 std::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 * se 的类型不同,我想这样做:

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> )

最佳答案

这样的事情可能会起作用:

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 arbitrary container .

关于c++ - 容器有重新绑定(bind)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50313655/

相关文章:

C++如何上下捕捉鼠标滚轮?

类似c++的语言

ios - 从 XCode 下载共享 App Group Container

c++ - 如何检查给定类型的变量是否可以取消引用?

c++ - 是否有类型特征来计算构造函数的总数?

c++ - 在存在通用构造函数的情况下,三元运算符上的 SFINAE 失败

c++ - 加速人员检测程序,使用 OpenCV 3.0 编写

c++ - DirectX HLSL 包含指令不起作用

flutter - Flutter InkWell小部件未通过容器的渐变和颜色显示

postgresql - Kubernetes:数据库和数据库用户