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()
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> .
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.
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.
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).
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.
Found it.
The problem was I wasn't calling the derived class' function.
Here is the fix:
static void Create()
{
mBase = T::CreateBase();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With