在 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 * 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>
)
最佳答案
这样的事情可能会起作用:
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/