Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static function in template class

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()
like image 725
Neil Avatar asked May 14 '12 16:05

Neil


People also ask

Can a static function be template?

The static declaration can be of template argument type or of any defined type. The statement template T K::x defines the static member of class K , while the statement in the main() function assigns a value to the data member for K <int> .

What happens when there is static member in a template class function?

The static member is declared or defined inside the template< … > class { … } block. If it is declared but not defined, then there must be another declaration which provides the definition of the member.

How do you define a static variable for a template class?

Each instantiation of function template has its own copy of local static variables. For example, in the following program there are two instances: void fun(int ) and void fun(double ). So two copies of static variable i exist. Each instantiation of class template has its own copy of member static variables.

Can we declare a template function as the friend of the class?

Template friendsBoth function template and class template declarations may appear with the friend specifier in any non-local class or class template (although only function templates may be defined within the class or class template that is granting friendship).


2 Answers

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.

like image 184
David Rodríguez - dribeas Avatar answered Sep 29 '22 07:09

David Rodríguez - dribeas


Found it.

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

Here is the fix:

static void Create()
{
    mBase = T::CreateBase();
}
like image 44
Neil Avatar answered Sep 29 '22 06:09

Neil