简体   繁体   English

我怎样才能组织C ++代码而不用太费力地思考是否有模板化的东西?

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

(I feel like this must be a duplicate, but I can't find it). (我觉得这必须是重复的,但我找不到它)。

Consider: 考虑:

airplane.hpp: airplane.hpp:

template<class T>
void wings();

void tail();

Now... where to define wings() and tail() ? 现在......在哪里定义wings()tail() I'd like to define them in the same place; 我想在同一个地方定义它们; I'd like not to think about the fact that wings() is templated and tail() isn't. 我不想考虑wings()是模板化而tail()不是模板的事实。 Maybe you'll see why I sometimes write: 也许你会明白为什么我有时会写:

airplane.hpp: airplane.hpp:

template<class T>
void wings();

void tail();

#ifndef airplane_cpp
#define header
#endif
#include "airplane.cpp"

airplane.cpp: airplane.cpp:

#define airplane_cpp
#include "airplane.hpp"

template<class T>
void wings() { }

#ifndef header
void tail() { }
#endif

But surely that's not the best way. 但当然这不是最好的方式。

edit: It seems it may be relevant to add that I'm programming on a TI DSP chip, where, according to the docs , the inline keyword has a defined consequence on generated code: 编辑:似乎可能有必要补充说我正在TI DSP芯片上编程,根据文档inline关键字对生成的代码有明确的后果:

The inline keyword specifies that a function is expanded inline at the point at which it is called rather than by using standard calling procedures. inline关键字指定函数在调用它的位置内联展开,而不是使用标准调用过程。 The compiler performs inline expansion of functions declared with the inline keyword. 编译器执行使用inline关键字声明的函数的内联扩展。

You can define all the functions in the header if you make them 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() {}

What you want can be achieved using the keyword export in front of your template. 你想要什么可以使用关键字来实现export在模板的前面。 Unfortunately this keyword has not gained considerable support across compilers. 不幸的是,这个关键字并没有得到编译器的大量支持。

In other words, practically speaking, you should define the body of your template in the header file. 换句话说,实际上,您应该在头文件中定义模板的主体。

From my point of view, compiler vendors should have do an effort to implement the same paradigm that is used for functions also for for templates. 从我的角度来看,编译器供应商应该努力实现用于模板的函数的相同范例。 Ie description of the interface should stay in the header files, description of the bodies bodies in cpp files. 即接口的描述应保留在头文件中,cpp文件中的主体描述。 Everything should be combined together during linking. 在链接期间,一切都应该组合在一起。 They has not done this. 他们没有这样做。 As we have it today, paradigms for functions and tempates are different. 正如我们今天所拥有的那样,功能和诱惑的范式是不同的。 Templates are compile time ony entities. 模板是compile time ony实体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM