我想将.h和.cpp分开作为模板类。这是我在做什么:
模板已被定义为错误。
无法识别的模板声明/定义错误
被占领。我的问题是我是否将* .cpp包含到* .h文件中。我们如何按预期构建项目?还是这个解决方案是绝对的?
// TestTemp.h
#ifndef _TESTTEMP_H_
#define _TESTTEMP_H_
template<class T>
class TestTemp
{
public:
TestTemp();
void SetValue(T obj_i);
T Getalue();
private:
T m_Obj;
};
#include "TestTemp.cpp"
#endif
// TestTemp.cpp
#include "TestTemp.h"
template <class T>
TestTemp<T>::TestTemp()
{
}
template <class T>
void TestTemp<T>::SetValue(T obj_i)
{
}
template <class T>
T TestTemp<T>::Getalue()
{
return m_Obj;
}
#include "TestTemp.h"
int main()
{
TestTemp<int> a;
a.Getalue();
return 0;
}
与普通类的成员函数不同,模板类的成员函数不能单独编译并链接到可执行文件中。模板的成员在使用时必须对编译器可见。那就是那篇可怕的文章中所有荒谬的东西。
最简单的方法是将定义直接放入模板定义中:
#ifndef TEST_H
#define TEST_H
template <class Ty>
class test {
public:
void f() { /* whatever */ }
};
#endif
这样做的缺点是较大的类变得不可读(参见Java)。因此,下一步是将定义移出模板,但将其保留在标题中:
#ifndef TEST_H
#define TEST_H
template <class Ty>
class test {
public:
void f();
};
template <class Ty>
void test<Ty>::f() { /* whatever */ }
#endif
许多人认为这仍然太混乱了,并希望将定义放入单独的文件中。没关系,但是无论何时使用原始标头,您都必须确保包含该单独的文件:
#ifndef TEST_H
#define TEST_H
template <class Ty>
class test {
public:
void f();
};
#include "test.imp"
#endif
这是文件“ test.imp”:
#ifndef TEST_IMP
#define TEST_IMP
template <class Ty>
void test<Ty>::f() { /* whatever */ }
#endif
请注意,“ test.imp”实际上是一个头文件,因此它通过中的#include "test.imp"
指令进入您的代码test.h
。它不能单独编译,所以应该不会有被命名.cpp
的扩展,这充其量是误导。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句