对在单独的.cpp文件中定义的模板函数的未定义引用

时间:2020-01-22 17:18:12

标签: c++

当我在undefined reference to wrapper<char>::Free()中调用此函数时,链接器~wrapper()收到一条错误消息。在我决定将整个类重写为模板类之后出现。

代码在这里,

wrapper.h

#include <iostream>
#ifndef WRAPPER_H
    #define WRAPPER_H
#define ALLOC_FAILED 3048

template <class T> struct wrapper
{
    T * data = nullptr;
    int dsize = 0;

    void Free();
    void Alloc(int s);
    void Copy(const wrapper<T> & other);

    wrapper(): data(nullptr), dsize(0){               }
    wrapper(int s)                    { Alloc(s);     }
    wrapper(const wrapper<T> & other) { Copy(other);  }
    ~wrapper()                        { Free();       }

    const wrapper<T> & operator = (const wrapper<T> & other){ Copy(other); return *this;}
};
#endif // WRAPPER_H

wrapper.cpp

#include "wrapper.h"
template <class T> void wrapper<T>::Free()
{
    if(data)
    {
        delete [] data;
        dsize = 0;
        data = nullptr;
    }
}
template <class T> void wrapper<T>::Alloc(int s)
{
    if(data) Free();
    data = new (std::nothrow) T[s];
    if(!data) throw ALLOC_FAILED;
    dsize = s;
}
template <class T> void wrapper<T>::Copy(const wrapper<T> & other)
{
    Alloc(other.dsize);
    for(int i = 0; i < this->dsize; i++) data[i] = other.data[i];
}

log:

||=== Build: Debug in wrapper (compiler: GNU GCC Compiler) ===|
obj\Debug\main.o||In function `ZN7wrapperIcED1Ev':|
wrapper.h|19|undefined reference to `wrapper<char>::Free()'|
||error: ld returned 1 exit status|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|

但是当结构不是模板时,代码运行得很好

wrapper.h

#include <iostream>
#ifndef WRAPPER_H
    #define WRAPPER_H
#define ALLOC_FAILED 3048

struct wrapper
{
    char * data = nullptr;
    int dsize = 0;

    void Free();
    void Alloc(int s);
    void Copy(const wrapper & other);

    wrapper(): data(nullptr), dsize(0){               }
    wrapper(int s)                    { Alloc(s);     }
    wrapper(const wrapper & other)    { Copy(other);  }
    ~wrapper()                        { Free();       }
    const wrapper & operator = (const wrapper & other){ Copy(other); return *this;}
};
#endif // WRAPPER_H

wrapper.cpp

#include "wrapper.h"

void wrapper::Free()
{
    if(data)
    {
        delete [] data;
        dsize = 0;
        data = nullptr;
    }
}
void wrapper::Alloc(int s)
{
    if(data) Free();
    data = new (std::nothrow) char[s];
    if(!data) throw ALLOC_FAILED;
    dsize = s;
}
void wrapper::Copy(const wrapper & other)
{
    Alloc(other.dsize);
    for(int i = 0; i < this->dsize; i++) data[i] = other.data[i];
}

谢谢您的回答。

0 个答案:

没有答案
相关问题