問題描述
我知道可以制作模板函數(shù):
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;
};
但是是否可以在模板中創(chuàng)建一個(gè)類,然后將那個(gè)類中的函數(shù)創(chuàng)建為模板?即:
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(){}
};
或者在某種程度上,類不是模板的一部分,但函數(shù)是?
or something to the extent, where the class is not part of a template, but the function is?
推薦答案
你的猜測(cè)是正確的.你唯一需要記住的是成員函數(shù)模板定義(除了聲明)應(yīng)該在頭文件中,而不是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.
這篇關(guān)于如何在類中創(chuàng)建模板函數(shù)?(C++)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!