c++ - 如何避免在库中为许多类型/函数重复键入模板特化

标签 c++ templates c-preprocessor

我在库 cpp 文件中有各种模板函数,它们通常如下所示:

template <class TT> TT im::BlockMultiplyAdd(const MtxView<TT> &src1, const MtxView<TT> &src2)
{
...
}

并且在 cpp 文件中也有实例化,如下所示:

template float im::BlockMultiplyAdd(const MtxView<float> &src1, const MtxView<float> &src2);
template double im::BlockMultiplyAdd(const MtxView<double> &src1, const MtxView<double> &src2);
template std::complex<float> im::BlockMultiplyAdd(const MtxView<std::complex<float>> &src1, const MtxView<std::complex<float>> &src2);
template std::complex<double> im::BlockMultiplyAdd(const MtxView<std::complex<double>> &src1, const MtxView<std::complex<double>> &src2);

我在头文件中也有声明。

现在我有很多这样的函数,我厌倦了为同一组四种类型一遍又一遍地输入相同的特化/声明。并非所有函数都具有相同的参数,但它们都具有相同的一组四种类型,它们是为这些类型构建的。

有什么方法可以让我制作预处理器宏或使用模板语法或更有效地安排我的代码,以便我可以减少输入(并使其更不容易出错)?

我是否应该将所有代码都放在模板的头文件中?静态库的优点/缺点是什么?

最佳答案

将它放入 header 中可能比依赖显式实例化更容易。但是如果你想这样做,你可以做类似的事情

// helper.h

// no include guard - important!
template TYPE im::BlockMultiplyAdd(const MtxView<TYPE> &src1, const MtxView<TYPE> &src2);
// similar stuff follows

然后在你的 cpp 文件中,多次包含 TYPE 每次都定义不同:

// instantiations.cpp

// template definition....

#define TYPE float
#include "helper.h"

#undef TYPE
#define TYPE double
#include "helper.h"

#undef TYPE
#define TYPE std::complex<float>
#include "helper.h"

#undef TYPE
#define TYPE std::complex<double>
#include "helper.h"
//etc...

关于c++ - 如何避免在库中为许多类型/函数重复键入模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24923386/

相关文章:

c++ - 如何去除QWizard中的水平线?

c++ - 关于 COM Release() 方法的问题

c++ - Copy ctor 在 VS2015 中未按预期运行

c++ - 我收到错误 'variable has incomplete type ' void '', and I can' t 找到问题所在

c - 防止间接级别内的宏扩展

c++ - 我怎样才能从模板派生两次,并让子类交互?

validation - 在CloudFormation模板中设置所需的参数输入

templates - 将 HTML 保存到 golang 模板变量

c++ - g++ __FUNCTION__ 替换时间

c++ - 包含#include 指令的宏定义