当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Polymorphic Explicit Template Instantiation

问题描述:

Have this basic hierarchy:

// header

class Base

{

virtual void method() { }

virtual ~method() { }

};

class Subclass : 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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: