【发布时间】:2012-05-07 07:02:59
【问题描述】:
我有一个相当标准的情况,我想通过以下方式使用模板类:
- 定义一个 .h 文件
- 是否包含 .cpp
在我尝试的所有其他编译器(即 g++ 和 clang/llvm)中,这都可以正常工作。在 Visual Studio 中,它告诉我该文件已被定义。
如果我手动将 .cpp 中的文本剪切并粘贴到 .h 文件中,那么一切正常。我的印象是,这正是 #include 应该做的。
我的预感是 Visual Studio 以某种方式不止一次编译 .cpp 文件(尽管我将 #pragma once 放在 .h 和 .cpp 文件上)。
发生了什么,如何让我的模板类在 VS 中运行?
代码如下:
.h:
#pragma once
template <class T>
class myVector
{
private:
void grow();
public:
int size;
int index;
T** words;
void pushBack(T* data);
inline T* operator[](int);
myVector(void);
~myVector(void);
};
#include "myVector.cpp"
.cpp:
#pragma once
#include "stdafx.h"
#include <cstdlib>
#include "myVector.h"
#include <iostream>
using namespace std;
template<class T>
myVector<T>::myVector(void)
{
this->size = 2000;
words = new T*[size];
index=0;
}
template<class T>
void myVector<T>::pushBack(T* input)
{
if(index<size)
{
words[index]=input;
}
else
{
grow();
words[index]=input;
}
index++;
}
template<class T>
T* myVector<T>::operator[](int i)
{
return words[i];
}
template<class T>
void myVector<T>::grow()
{
//cout<<"I grew:"<<endl;
size*=2;
words = (T**)realloc(words,size*sizeof(T*));
}
template<class T>
myVector<T>::~myVector(void)
{
delete[] words;
}
【问题讨论】:
-
AFAIK 将模板声明与定义分开被认为是不好的做法。至少不要使用 .cpp,使用 .tpp。充其量,在您声明它们的地方定义它们。这对你和编译器来说都少了很多工作。
标签: c++ visual-studio templates