实现模板类中定义的非模板方法

实现模板类中定义的非模板方法

本文介绍了实现模板类中定义的非模板方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想定义在模板类中声明的方法,但该方法不依赖于模板参数时,请让我在包含文件中将其定义为:

When I want to define a method declared in a template class, but that the method doesn't depend on the template parameters, have I to define it in the include files as :

template class<typename T>
void MyClass::myMethod()
{
   ...
}

或者我可以在cpp文件中将其定义为:

or may I define it in the cpp file as :

void MyClass::myMethod()
{
   ...
}

?

谢谢.

推荐答案

您需要像这样定义您的方法:

You'll need to define your method like this:

template class<typename T>
void MyClass<T>::myMethod()
{
    // Method Body
}

这样做的原因是该方法实际上取决于template参数.请记住,每个方法都可以访问特殊变量 this ;在方法调用期间, this 实际上是传递给方法的参数. this 的类型会根据对象实例化期间指定的模板参数而变化,因此,所有方法都必须是模板方法,才能容纳所有形式的 this .

The reason for this is that the method actually is dependent on the template parameter. Remember that every method has access to the special variable this; during the method call this is actually a parameter passed to the method. this changes in type depending on the template parameter specified during object instantiation and, as such, all methods must be template methods in order to accommodate all forms of this.

这篇关于实现模板类中定义的非模板方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:58