如何在类中创建模板函数?(C++)

How to create a template function within a class? (C++)(如何在类中创建模板函数?(C++))
本文介绍了如何在类中创建模板函数?(C++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以制作模板函数:

I know it's possible to make a template function:

template<typename T>
void DoSomeThing(T x){}

并且可以制作模板类:

template<typename T>
class Object
{
public:
    int x;
};

但是是否可以在模板中创建一个类,然后将那个类中的函数创建为模板?即:

but is it possible to make a class not within a template, and then make a function in that class a template? Ie:

//I have no idea if this is right, this is just how I think it would look
class Object
{
public:
    template<class T>
    void DoX(){}
};

或者在某种程度上,类不是模板的一部分,但函数是?

or something to the extent, where the class is not part of a template, but the function is?

推荐答案

你的猜测是正确的.你唯一需要记住的是成员函数模板定义(除了声明)应该在头文件中,而不是cpp中,尽管它不是必须在类声明本身的主体中.

Your guess is the correct one. The only thing you have to remember is that the member function template definition (in addition to the declaration) should be in the header file, not the cpp, though it does not have to be in the body of the class declaration itself.

这篇关于如何在类中创建模板函数?(C++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)