In the C++ standard library allocators
can be rebound.
std::allocator<int>::rebind<double>::other
gives std::allocator<double>
.
Is there an easy way to do this with containers?
The reason is that I have a function that multiplies containers elements by a scalar.
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;
}
But if e * s
is not the same type as e
, I want to do this:
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;
}
(I guess it is not clear why I would want the output to be the same class of container as the input, but I guess that is the expected result.)
I could use template template arguments (as in template<template<typename> class V>
) but it seems to have its problems too.
Do we need some sort of container_traits<V>::rebind
? (e.g. container_traits<std::vector<double, myallocator<double> >>::rebind<int>::other
-> std::vector<int, myallocator<double>::rebind<int>::other>
)