开发者

Polymorphic Explicit Template Instantiation

开发者 https://www.devze.com 2023-01-26 02:22 出处:网络
Have this basic hierarchy: // header class Base { virtual void method() { } virtual ~method() { } }; class Su开发者_运维知识库bclass : Base

Have this basic hierarchy:

// header

class Base
{
    virtual void method() { }
    virtual ~method() { }
};

class Su开发者_运维知识库bclass : Base
{
    virtual void method() { }
    virtual ~method() { }
};

I wish to subclass Base with two explicit variations (without having to provide two implementations of Subclass if possible), so it has been suggested to use explicit template instantiation:

// header

class Base
{
    virtual void method() { }
    virtual ~method() { }
};

class Base1 : public Base { };
class Base2 : public Base { };

template <typename T>    
class Subclass : public T
{
    virtual void method();
    virtual ~method() { }
};

// cpp

template <typename T>
void Subclass<T>::method()
{
}

template class Subclass<Base1>;
template class Subclass<Base2>;

I'm getting this error:

there are no arguments to 'method' that depend on a template parameter, so a declaration of 'method' must be available

Is this the correct approach? I would clearly have to template Base in order to get this to compile, but with what?


You should to put the definition of your template class and functions in the header file (it must be visible to who uses them).

Only complete specializations can be declared only (and defined where your code has no visibility).

Besides, if you want to define a function of a class template out of the class (as you did) you must declare it as a template:

template< typename T > 
void Class<T>::method( )
{
}

Anyway, if I recall correctly, the error you quoted is given when you use the function method which is provided by the typename you're inheriting from (I think you haven't posted the piece of code that generates the error...): it can only be found when the template is actually instantiated, thus you need to explicitly say it depends on the template parameter.

Call method in this way:

T::method();


Brief summary of the problem and solution:

To use a method from a templated base class requires either using the template parameter:

T::method();

or simply using "this" to allow it to be found without explicitly knowing the template parameter:

this->method();

Thanks to those that pointed me towards finding this solution, I wasn't aware of this. Also wish to point out there isn't a problem with putting the templates in the cpp file.

0

精彩评论

暂无评论...
验证码 换一张
取 消