模板和单独的编译 [英] Templates and separate compilation
问题描述
我想用C ++编写一个单独编译的程序,我写了:
I want to write a program in C++ with separate compilation and I wrote this:
main.cpp
#include <iostream>
#include "Stack.h"
using namespace std;
int main(int argc,char* argv[])
{
Stack<int> st;
st.push(1);
return 0;
}
Stack.h
#ifndef _STACK_H
#define _STACK_H
template<typename T>
class Stack
{
private:
struct Node
{
Node* _prev;
T _data;
Node* _next;
};
int _size;
Node* _pos;
public:
Stack();
T pop();
void push(T const &el);
int getSize() const;
};
#endif
Stack.hpp
Stack.hpp
#include "Stack.h"
#include <malloc.h>
template <typename T>
Stack<T>::Stack()
{
_size = 0;
_pos = (Node*)malloc(sizeof(Node));
_pos->_prev = NULL;
_pos->_next = NULL;
}
template <typename T>
T Stack<T>::pop()
{
if (_size == 0)
return NULL;
T tmp = _pos->_data;
if (_pos->_prev == NULL)
free(_pos);
else
{
_pos->_prev->_next = _pos->_next;
if (_pos->_next != NULL)
{
_pos->_next->_prev = _pos->_prev;
}
free(_pos);
}
_size--;
return tmp;
}
template <typename T>
void Stack<T>::push(T const &el)
{
Node* n = (Node*)malloc(sizeof(Node));
_pos->_next = n;
n->_prev = _pos;
n->_data = *el;
_pos = n;
_size ++;
}
template<typename T>
int Stack<T>::getSize() const {return _size;};
我用g ++编译程序,得到这个错误:
I compiled the program with g++ and I get this error:
ccyDhLTv.o:main.cpp:(.text+0x16): undefin
ed reference to `Stack<int>::Stack()'
ccyDhLTv.o:main.cpp:(.text+0x32): undefin
ed reference to `Stack<int>::push(int const&)'
collect2: ld returned 1 exit status
我知道问题是因为我使用模板,但我不知道如何修复
I know that the problem is because I'm using templates but I do not know how to fix it.
OS - Windows
编译行 - g ++ main.cpp Stack.h Stack.hpp -o main.exe
OS - Windows
compilation line - g++ main.cpp Stack.h Stack.hpp -o main.exe
推荐答案
模板类需要在头文件中包含方法定义。
Template classes need to have the method definitions inside the header file.
移动你在 .cpp
文件中的代码,或者创建一个名为 .impl
或
.imp
,将代码移动到那里,并将其包含在标题中。
Move the code you have in the .cpp
file inside the header, or create a file called .impl
or .imp
, move the code there, and include it in the header.
编译器需要知道方法定义来为所有专业化生成代码。
The compiler needs to know the method definitions to generate code for all specializations.
在您提出要求之前,没有办法将实现保留在标题之外。
Before you ask, no, there is no way to keep the implementation outside the header.
这篇关于模板和单独的编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!