【发布时间】:2016-10-16 20:39:55
【问题描述】:
注意:以下问题是关于Template Method Design Pattern 和C++ 函数模板。为了区分两者,我将在引用设计模式时使用 斜体,在引用 C++ 模板时使用 粗体。
模板方法模式的想法是使算法的某些部分可交换。这通常通过继承来实现,其中子类提供插入基类算法的具体实现。但是,如果钩子方法需要是 模板,这将不起作用,因为 模板 不能是虚拟的。这是一个无法编译的简单示例:
class Base
{
public:
// This is the template method
template <typename T>
void doSomething(T input)
{
//...
auto converted = ConvertInput(input);
//...
std::cout << converted;
}
protected:
//compile error "member function templates cannot be virtual"
template <typename T>
virtual T ConvertInput(T input) = 0;
};
class Derived : public Base
{
protected:
template <typename T>
T ConvertInput(T input)
{
return 2 * input;
}
};
int main()
{
Derived d;
d.doSomething(3);
}
有没有办法实现使用函数模板钩子的模板方法?
我对在任何地方使用 Base 类作为类型不感兴趣。我将始终使用具体的特定类型来实现最大的编译时优化。所以这个问题的另一种表述是:我怎样才能创建多个类Derived-1 .. Derived-n,它们具有函数模板,它们在实现之间共享一个公共代码框架?
【问题讨论】:
-
CRTP。使
Base以Derived作为模板参数。通过static_cast<D*>(this)->ConvertInput拨打ConvertInput -
T使用的类型集是否有任何限制? -
@Yakk 是的,但只有隐含的。例如。其中一个实例需要使用迭代器,它可以是任何东西。
-
@nico 迭代可以被类型擦除。 ;)
标签: c++ templates design-patterns template-method-pattern