如何实现具有两个argment的模板类 [英] How to implement a template class with two argment

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

问题描述

全部!



我正在编码数组模板类。



头文件是

Hi, All!

I'm coding array template class.

Header file is

template <class T, int N>
class CMyArray
{
public:
    CMyArray(int _len=0);
    ~CMyArray();
protected:
    int	    nSize;
    int	    m_nMaxSize;
    T *	    data;
}



和cpp文件是


and cpp file is

#include "MyArray.h"

template <class T, int N>
CMyArray<T, N>::CMyArray(int _len/* = 0*/) 
	: nSize(0)
	, m_nMaxSize(_len)
	, data(_len > 0 ? new T[_len] : NULL) 
{
    if(m_nMaxSize > 0) 
	memset(data, 0x00, m_nMaxSize * sizeof(T));
}



和通话代码是


and calling code is

#include "MyArray.h"

typedef CMyArray<USHORT, 256>	ArrayUShort;
ArrayUShort arrIDs;
...



然后在编译时,链接错误。

但是,在没有cpp文件的工具的情况下写入头文件,


then while compile, link error.
but, writing at header file without cpp file's implement,

template <class T, int N>
class CMyArray
{
public:
    CMyArray(int _len=0)
        : nSize(0)
        , m_nMaxSize(_len)
        , data(_len > 0 ? new T[_len] : NULL)
    {
        if(m_nMaxSize > 0)
            memset(data, 0x00, m_nMaxSize * sizeof(T));
    }
    ~CMyArray();
protected:
    int     nSize;
    int     m_nMaxSize;
    T *     data;
}



以上代码没问题。

但是我想在cpp文件中实现。


above code has no problem.
but I want to implement in cpp file.

推荐答案

您不能将模板函数定义放在cpp文件中。好吧,你可以,但如果这样做,只有该cpp文件中的代码才能使用该类/函数!否则,您会收到链接器错误。



错误的原因是编译器不会为模板函数生成代码,除非在某处调用它。如果在cpp文件中调用它,则编译器会尝试从其强制生成函数。但是,如果实现既不在头文件中也不在那个特定的cpp文件中,那么它就不能!因此,将不会生成该函数,并且链接器将会抱怨。
You cannot put a template function definition in a cpp file. Well, you can, but if you do so, only code within that cpp file will be able to use that class/function! Otherwise, you get a linker error.

The reason for the error is that the compiler will not generate code for a template function unless it is called somewhere. If it is called within a cpp file, then the compiler tries to generate the function from it's impementation. However, if the implementation is neither in the header file nor in that particular cpp file, then it can't! As a result, the function will not be generated, and the linker will complain.


这篇关于如何实现具有两个argment的模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆