C++ : How to make a specific binary (executable) for each trait?

标签 c++ templates metaprogramming

我正在从事一个有很多特征类型的项目。如果我在同一个代码库中编译每个特征,发布的二进制文件将非常大。

我正在考虑使用宏为每个特定特征构建一个二进制文件——从业务逻辑的角度来看,这非常有意义。

但是,我意识到,如果我想减少代码库,我需要在每个模板 cpp 文件的末尾都有这么长的 if/elif 堆。这听起来像是一件非常乏味的事情。

我想知道您以前是否遇到过此类问题,这里最巧妙的解决方案是什么?

#include "MyTraits.hpp"
#include "Runner.hpp"
int main(){
    #if defined USE_TRAIT_1
    Runner<Trait1> a;
    #elif defined USE_TRAIT_2
    Runner<Trait2> a;
    #elif defined USE_TRAIT_3
    Runner<Trait3> a;
    #endif
    return 0;
}

最佳答案

如果你想在特定的编译单元中显式实例化模板,你应该使用 extern template 关键字。

// Runner.hpp
//define your template class
template <class runner_trait>
class Runner {
...
};

//This tells the compiler to not instanciate the template,
// if it is encounterd, but link to it from a compilation unit.
// If it is not found, you will get a linker errer.
extern template Runner<Trait1>;
extern template Runner<Trait2>;
extern template Runner<Trait3>;

Runner_trait1.cpp

// the template class keyword tell the compiler to instanciate the template in this compilation unit.
template class Runner<Trait1>;

// The files for Runner_trait2.cpp and  Runner_trait3.cpp look identical,
// except for the trait after Runner

关于C++ : How to make a specific binary (executable) for each trait?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45447650/

相关文章:

c++ - 当我使用 expire_at 时,Boost deadline_timer 没有生成事件?

c++ - 媒体文件无法切换播放

c++ - 用于检测函数是否存在的 C++ 元函数问题

c++ - 使用模板元编程将模板函数 bool 参数转置为运行时函数参数

定义函数闭包的 Pythonic 方式

c++ - C/C++ 结构实际上是如何工作的?

C++如何实现进程间socket通信?

c++ - 为什么出现 "no matching overload found"错误,即使我定义了它们

C++ 模板元编程 : how to create and iterate over list of types that are "typedefs" in template class.

c++ - 模板特化继承自特定子类