【发布时间】:2018-07-19 14:37:05
【问题描述】:
所以我有大量这个模板的模板特化:
template <typename T> // Same
struct foo { // Same
using type_name = T; // Same
foo(const int base) : _base(base) {} // May take other parameters
void func(const T& param) {} // This function signature will be the same but body will differ
int _base; // Same but may have more members
}; // Same
所以一个示例专业化是:
template<>
struct foo<float> {
using type_name = T;
foo(const int base, const int child) : _base(base), _child(child) {}
void func(const T& param) { cout << param * _child << endl; }
int _base;
int _child;
};
显然这是一个玩具示例,_func 的主体将更多地参与其中。但我认为这表达了这个想法。我显然可以制作一个宏来帮助处理样板文件,并将该函数的专用版本的实现放在一个实现文件中。
但我希望 C++ 为我提供了一种无需宏就能做到这一点的方法。是否有另一种方法可以避免一遍又一遍地编写样板文件?
【问题讨论】:
-
// This function signature will be the same but body will differ让我想到了继承而不是模板。 -
这里实际上很少有样板文件。您可以定义
template <typename T> struct foo_base { using type_name = T; int _base; };并从中派生foo专业化 - 这将为每个专业化节省两行代码。 -
@IgorTandetnik 呃,我认为你是对的 :( 没有比这更好的了 T.T
-
@Ron 我想我一直认为它们是标题。
标签: c++ templates template-specialization boilerplate template-classes