2

I'm working on a piece of code and have been banging my head against the proverbial wall for quite some time now. I am kind of new to the whole concept of templates and so would appreciate any and all help I can get on the following problem:

I am trying to build a object builder that takes an allocator as argument as such:

class Allocator {
public:
    allocate(unsigned int size, unsigned int alignment);
    template <class T>
    T* allocate_object() { return allocate(sizeof(T), alignof(T)); }
};

template <class ALLOCATOR>
class Builder {
public:
    Builder(ALLOCATOR& a) : a(a) {}
    void build_something() {
        int* i = a.allocate_object<int>();
    }
private:
    ALLOCATOR& a;
};

When I try to call the 'build_something' function with my allocator i get the following compilation error: "error: expected primary-expression before 'int'"

The allocator works on its own as intended but can not be used as a template argument as in the example. So, is there something I can do to fix this without having to drop the template function in the allocator?

Preferably I would have liked to use polymorphism to send an allocator (base class) object pointer to the builder but apparently you can't have virtual template functions. :)

Thanks for the time! :) -Maigo

Maigo
  • 69
  • 4

1 Answers1

3
    int* i = a.template allocate_object<int>();

C++ template gotchas

Community
  • 1
  • 1
Anycorn
  • 50,217
  • 42
  • 167
  • 261
  • More good reading material: [What is the ->template, .template and ::template syntax about?](http://www.comeaucomputing.com/techtalk/templates/#templateprefix) – ildjarn Apr 21 '11 at 09:58