I have a non-templated class called Allocator
which implements
template<class T>
Buffer<T> allocate(size_t n) { ... }
This function invokes a virtual unimplemented non-templated function in the same class
virtual Buffer<std::byte_t> allocate(size_t size, size_t align) = 0;
This non-templated allocate()
function is overriden by derived classes. The idea is that the non-templated allocate function allocates std::byte
s with given alignment and as such can be used by the templated function. The templated function is a essentially a pretified call to the byte-allocation function. It automatically picks up the alignment of the type T
and calls
allocate(n * sizeof(T), alignof(T));
which works fine when derived classes are used.
Derived classes would need to implement the byte-allocation function and automatically have the typed-object-allocation function through inheritance:
So, I have a class Page : public Allocator
that does exactly that but it seems that it cannot call the allocate<T>(...)
function. If I do
Page page{...};
... = page.allocate<int>(10);
then I get the following error from VSCode intellisense:
A pointer to a bound function may only be used to call the function
and
expected primary-expression before '>' token
from g++ 12.1.0 Rev3 (the token that g++ specifically shows is the >
after <int
). It seems that g++ won't even pretend to see the allocate<T>(...)
as existing.
On the other hand, doing this works fine:
((Allocator *) &page)->allocate<int>(10);
Is there some specific reason why the derived class cannot invoke the templated function in the base class directly? Why do I have to cast it to a pointer of the base class?