4

I'm trying to create a sort of factory class in a template. I wanted to do something like a pure virtual function, but it needs to be static as I'm using the function to create types.

What I want to happen is when I declare a class, the template calls the static function. The static function is actually declared in the templatised class.

I've got as far as:

class Base
{

};

template<typename T>
class Type : public Base
{
public:
    static void Create()
    {
        mBase = CreateBase();
    }

private:
    static Base* CreateBase();

    static Base* mBase;
};

class MyType : public Type<MyType>
{
private:        
    static Base* CreateBase()
    {
        return new MyType;
    }
};

template<typename T>
Base* Type<T>::mBase = NULL;

void test()
{
    MyType::Create();
}

I get a link time error:

undefined reference to `Type<MyType>::CreateBase()
1

2 Answers 2

2

The CreateBase function is defined in the base type, so just call it:

template<typename T>
class Type : public Base
{
public:
    static void Create()
    {
        mBase = Base::CreateBase();
    }
//...

There is no need to declare another CreateBase in the template.

Sign up to request clarification or add additional context in comments.

2 Comments

The problem isn't that I can't call it, it's that this code doesn't link.
@Neil: In Create you are calling Type<>::CreateBase that is not defined, and thus the linker fails. The proposed solution is not calling Type<>::CreateBase (don't even declare it!) and directly call Base::CreateBase, which is defined in MyType and will link appropriately.
1

Found it.

The problem was I wasn't calling the derived class' function.

Here is the fix:

static void Create()
{
    mBase = T::CreateBase();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.