使用模板的动态多态性行为
Behaviour of dynamic polymorphism using templates?
几年前,在一次面试中,有人向我展示了一些看起来很可怕的代码,这些代码的行为与动态多态性相同,但使用了模板。我指的不是模板的正常用法。
如何使用模板来实现相当于运行时多态性的行为?
更新:我认为它与这个有关:
http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern Static_polymorphism
使用奇怪循环模板模式(CRTP),您可以实现类似于编译时多态性的功能。下面是一个简单的例子:
template<typename DERIVED>
struct base
{
public:
void f() const
{
static_cast<DERIVED&>( *this ).f_();
}
};
struct derived1 : public base<derived1>
{
void f_() const
{
std::cout << "Derived1!n";
}
};
struct derived2 : public base<derived2>
{
void f_() const
{
std::cout << "Derived2!n";
}
};
template<typename DERIVED>
void call( const base<DERIVED>& e )
{
e.f(); //compile-time resolved (Possibly inlined) polymorphic call here
}
int main()
{
derived1 d1;
derived2 d2;
call( d1 );
call( d2 );
}
以上代码输出:
derived1 !
derived2 !
相关文章:
- 多态性和功能结合
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- C++boost序列化多态性问题
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 如何在多线程中正确使用unique_ptr进行多态性?
- 具有智能指针的多态性
- 在 C++ 中在堆栈上创建实例时如何保持多态性?
- 继承/多态性 - 我是否被迫使用"protected"变量?
- C++ 多态性在代码::块 17.12 中不起作用
- C++ 泛型和多态性:这种模式可行吗?
- cmake add_custom_command + Xcode:多输出 = 多命令调用
- 为什么我们实际上需要运行时多态性?
- 如何在这个简单的最小示例中实现多态性?
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- 无法初始化已知大小的矢量指针,该大小不会因多态性而更改
- C++:用单个函数调用替换多个索引相等性测试
- C++ 具有多父多态层次结构的 VTable 实现
- 如何解析具有多个多态输入的方法调用
- C++中多变量正态/高斯分布的样本