我怎样才能组织C++代码而不费力地考虑某些内容是否被模板化

How can I organize C++ code without thinking too hard about whether something is templated?

本文关键字:是否 不费力 代码 C++      更新时间:2023-10-16

(我觉得这一定是重复的,但我找不到它)。

考虑:

飞机.hpp:

template<class T>
void wings();
void tail();

现在。。。 在哪里定义wings()tail()?我想在同一个地方定义它们;我不想考虑wings()是模板化而tail()不是的事实。也许你会明白我为什么有时会写:

飞机.hpp:

template<class T>
void wings();
void tail();
#ifndef airplane_cpp
#define header
#endif
#include "airplane.cpp"

飞机.cpp:

#define airplane_cpp
#include "airplane.hpp"
template<class T>
void wings() { }
#ifndef header
void tail() { }
#endif

但这肯定不是最好的方法。

编辑:似乎有必要补充一点,我正在TI DSP芯片上编程,根据文档,inline关键字对生成的代码具有定义的后果:

inline 关键字指定函数在 它被调用,而不是使用标准调用过程。这 编译器对使用内联声明的函数执行内联扩展 关键词。

如果将它们设置为inline,则可以在标头中定义所有函数:

template<class T>
inline void wings() {}
// inline not really needed here, but if you don't want to think about it...
inline void tail() {}

您可以使用模板前面的关键字 export 来实现您想要的。不幸的是,这个关键字在编译器中没有得到相当大的支持。

换句话说,实际上,您应该在头文件中定义模板的正文。

从我的角度来看,编译器供应商应该努力实现用于函数的相同范例,也用于模板。 即接口的描述应该保留在头文件中,正文的描述应该保留在 cpp 文件中。在链接过程中,所有内容都应组合在一起。他们没有这样做。正如我们今天所拥有的,函数和诱惑的范式是不同的。模板是compile time ony实体。