模板类多文件项目 - 如何?

时间:2012-11-07 11:46:19

标签: c++ class templates

  

可能重复:
  Why can templates only be implemented in the header file?
  Why should the implementation and the declaration of a template class be in the same header file?

我正在开展一个项目,我需要“堆栈”来保存数据。但是我不想为每个文件类型编写不同的版本(我不想使用向量)。

所以我正在尝试使用模板类,这是我的代码:

StructStack.h

#ifndef STRUCTSTACK_H_
#define STRUCTSTACK_H_

template <class AnyType> class StructStack {
    StructStack();
    ~StructStack();
    struct Element {
        Element *pointer;
        AnyType value;
    };
    Element *pointerToLastElement;
    int stackSize;
    int pop();
    void push(int value);
    int size();
};

#endif

StructStack.cpp

#include "stdafx.h"
#include "StructStack.h"
#include <iostream>
using namespace std;


template <class AnyType> void StructStack<AnyType>::StructStack() {
    //code
}

template <class AnyType> void StructStack<AnyType>::~StructStack() {
    //code
}

template <class AnyType> AnyType StructStack<AnyType>::pop() {
    //code
}

template <class AnyType> void StructStack<AnyType>::push(AnyType value){
    //code
}

template <class AnyType> AnyType StructStack<AnyType>::size() {
    //code
}

如果我尝试编译这两个文件,我会收到一堆编译错误。我在网上看到,在多文件项目中创建模板类很难。

那怎么办呢?

4 个答案:

答案 0 :(得分:2)

您只需将函数的定义放在头文件中即可。 你在StructStack.cpp内写的所有内容都应该在课程定义之后进入StructStack.h

答案 1 :(得分:1)

您可以通过在StructStack.cpp中放置所有定义(您当前在[{1}}中拥有的代码)并删除前者来解决此问题。编译器需要访问实现代码,以便根据需要实例化类模板。

答案 2 :(得分:1)

每个需要使用它的文件都需要看到模板化代码。

在专业化或使用之前,它不会被编译。

基本上,如果你想在不同的文件中使用它,你必须把它放在头文件中,然后包含它。当您实际使用具有特定类型的模板时,代码将在其使用的上下文中生成。

答案 3 :(得分:0)

C ++模板代码应始终放在头文件中,以便在您要实例化模板的每个翻译单元中都可以看到实现。如果您愿意,可以将代码分隔为* .h和* .cpp文件,但您仍然应该在* .h文件末尾添加#include * .cpp文件。