[英]How to avoid repeated typing of template specializations in library for many types / functions
我在庫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);
我在頭文件中也有聲明。
現在,我有許多這樣的功能,而且我討厭為一遍又一遍地為同一組四個類型鍵入相同的專業化/聲明。 並非所有函數都具有相同的參數,但是它們都具有為其構建的相同的四種類型集。
有什么辦法可以使預處理程序宏或使用模板語法或更有效地安排代碼,從而減少鍵入(並減少錯誤的發生)?
我是否應該將所有代碼都放在模板的頭文件中? 靜態庫的優點/缺點是什么?
將其放入標頭而不是依賴顯式實例化可能更容易。 但是,如果您想這樣做,可以做類似的事情
// 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...
最后,我這樣做的方法是為每次出現的事件創建一個臨時宏,如下所示:
template <class TT> void im::BlockMultiply(MtxView<TT> dst, const MtxView<TT> &src1, const MtxView<TT> &src2)
{
...
}
#define INST(TT) template void im::BlockMultiply(MtxView<TT> dst, const MtxView<TT> &src1, const MtxView<TT> &src2)
INST(float); INST(double); INST(std::complex<float>); INST(std::complex<double>);
#undef INST
剪切和粘貼並不是一件容易的事,因為除了在template
之后刪除<class TT>
之外,不需要進行任何更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.