包括模板标题解决方案

时间:2011-12-16 18:59:01

标签: c++ templates include

编程有多糟糕?我是一个可怕的人吗?

//templates.cpp
template <typename TYPE> void some_func(int arg1, ...)
{
  //do stuff
}

然后:

//templates.h
#ifndef TEMPLATES_H_INCLUDED
#define TEMPLATES_H_INCLUDED

#include "templates.cpp"
template <typename TYPE> void some_func(int arg1, ...);

#endif

最后:

//main.cpp
#include "templates.h"

int main ...
some_func<int>(5);
std::fprintf(stderr, "ZOMG IT WORKT!\n!\n!\n!");

对我来说很好。它似乎解决了我们很多人n00bs关于如何正确地分离模板的.cpp和.h文件然后包含它们而没有编译器错误的无休止的问题。

templates.h文件中的行#include "templates.cpp"基本上等同于将声明和源代码都包含在一个文件中。但是这种方法可以很好地区分它们,这正是我们所有人都想要的。

2 个答案:

答案 0 :(得分:3)

  1. 通常,带有模板实现的文件会有不同的扩展名。例如,boost使用.ipp,其他人可能使用.inl
  2. 这不是我们真正想要的。我们想要的是单独编译模板的实现以减少编译时依赖性。

答案 1 :(得分:2)

这实际上是一种非常常见的方法,除了我认为你应该把

#include "templates.cpp"

*.h end 而不是在开头。

此外,您仍应将这些功能标记为inline

相关问题