krsi
krsi

Reputation: 1115

Factory function template that creates objects from a class template?

I have two factory function templates makeObjectA and makeObjectB which create instances from a class template (ClassTemplateA and ClassTemplateB). The makeObject functions call another function template (create) which actually instantiates objects and performs some generic initialization. The create function template thus needs two template parameters, one that specifies what type of object to create, and another that is passed as the object's template argument.

Here is an example of what I'm trying to do, but I don't understand why this code won't compile, and how to fix it?

factory.h(17): error C2988: unrecognizable template declaration/definition

ClassTemplates.h

#pragma once

template <typename T>
class ClassTemplateA {

public:
    ClassTemplateA() {}

};

template <typename T>
class ClassTemplateB {

public:
    ClassTemplateB() {}

};

Factory.h

#pragma once
#include "ClassTemplates.h"

template <typename T>
ClassTemplateA<T>& makeObjectA()
{
    return create<ClassTemplateA, T>();
}

template <typename T>
ClassTemplateB<T>& makeObjectB()
{
    return create<ClassTemplateB, T>();
}

template<typename TClassTemplate, typename T>
TClassTemplate<T>& create()
{
    TClassTemplate<T>* object = new TClassTemplate<T>();

    // Do some generic initialization after construction.

    return *object;
};

Main.cpp

#include "ClassTemplates.h"
#include "Factory.h"

int main() 
{
    ClassTemplateA<int>& objectA = makeObjectA<int>();
    ClassTemplateB<int>& objectB = makeObjectB<int>();
}

Upvotes: 2

Views: 582

Answers (1)

Jarod42
Jarod42

Reputation: 217293

You want template template argument:

template <template <typename> class TClassTemplate, typename T>
TClassTemplate<T>& create()
{
    TClassTemplate<T>* object = new TClassTemplate<T>();

    // Do some generic initialization after construction.

    return *object;
};

Upvotes: 4

Related Questions