当我使用静态多态性(CRTP)时,有没有一种好的方法来给多态方法命名?
template <class Derived>
struct Base
{
void interface()
{
// ...
static_cast<Derived*>(this)->implementation();
// ...
}
static void static_func()
{
// ...
Derived::static_sub_func();
// ...
}
};
struct Derived : Base<Derived>
{
void implementation();
static void static_sub_func();
};
因为,据我所知,接口(interface)和实现不能具有相同的名称(就像它们是虚拟的一样)。如果类层次结构很深,那就有点尴尬了。
也许有一些好的方法来处理它?或者也许我错了?
最佳答案
我的方法是避免继承(无论 CRTP 感觉多么可爱),而是使用聚合。类模板提供接口(interface),并依次提供具有实现的委托(delegate)类。它看起来像这样:
template <class Delegate>
struct Interface
{
void do_something()
{
// ...
delegate.do_something();
// ...
}
Delegate delegate;
};
这有一个缺点,即向委托(delegate)对象提供构造函数参数比较尴尬,但管理起来并不太困难。
关于c++ - C++ 静态多态性和方法名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13645593/