I have a class template that supports different allocators for its member:
template<typename Alloc>
class Foo
{
std::vector<int, Alloc<int>> data;
// other members ...
}
Consider a function func
that accepts a const Foo&
. As the allocator is a part of Foo
's type, I need to declare it as a template as well:
template<typename Alloc>
void func(const Foo<Alloc>& foo);
In my understanding, when only looking at a const Foo&
the allocator does not matter and therefore all instantiations of func
would be identical. Besides code bloat, this introduces unwanted dependencies.
- Is there a way to make
func
unaware of the allocator? - Would it be safe to settle for one allocator (e.g.
std::allocator
) in the function (which then no longer needs to be a template) and upon calling it do areinterpret_cast
fromFoo<MyCostumAllocator<int>>
toFoo<std::allocator<int>>
?
I know of std::pmr::polymorphic_allocator
which does not suffer from this problem (as long as you only use pmr allocators), but this is not an option for me.
CodePudding user response:
The issue you see with func
is secondary. Different instantiations of Foo
are completely different distinct types. Hence, also different instantiations of func
must be different functions.
However, if the interface of Foo
does not depend on the allocator, you can add a allocator unaware base class:
struct Foo_base {
// virtual interface
};
template <typename Alloc>
struct Foo : Foo_base {
std::vector<int, Alloc<int>> data;
};
void func(const Foo_base& foo);