CRTP的静态多态性:使用基类调用派生方法 [英] Static Polymorphism with CRTP: Using the Base Class to Call Derived Methods
问题描述
C ++中virtual
的主要优点之一是能够使用基类(指针或引用)来调用派生方法.
One of the main benefits of virtual
in C++ is being able to use the base class (pointer or reference) to call derived methods.
我正在阅读使用CRTP实现静态多态性,但是我可以无法理解如何使用此技术来实现我上面提到的内容,因为当需要模板时,我无法将函数声明为类型为Base
.
I'm reading up on using CRTP to implement static polymorphism, but I can't understand how to achieve what I've mentioned above using this technique, because I can't declare a function as taking type Base
when this requires a template.
在我看来,只需使用函数重载就可以实现本文中描述的内容,因此,我敢肯定,这项技术还必须有更多的内容.
It seems to me that what is described in the article could be achieved by simply using function overloading, so I'm sure that there must be more to this technique.
(PS: this exact problem is alluded to in a comment to an answer to this question, but unfortunately no one had replied to it: "What vtables truly provide is using the base class (pointer or reference) to call derived methods. You should show how it is done with CRTP here.")
这是我的最小代码,它给出错误在'&'标记之前缺少模板参数 void Print(Base& Object)".
Here is my minimal code, which gives the error "missing template arguments before ‘&’ token void Print(Base& Object)".
#include <cstring>
#include <iostream>
template <typename Derived>
struct Base
{
std::string ToStringInterface() { return static_cast<Derived*>(this)->ToString(); }
std::string ToString() { return "This is Base."; }
};
struct Derived : Base<Derived>
{
std::string ToString() { return "This is Derived."; }
};
void Print(Base& Object)
{
std::cout << Object->ToStringInterface() << std::endl;
}
int main()
{
Derived MyDerived;
// This works, but could have been achieved with a function overload.
std::cout << MyDerived.ToStringInterface() << std::endl;
// This does not work.
Print(MyDerived);
}
推荐答案
好,您需要声明print一个模板函数:
Well, you need to declare print a template function :
template<class T>
void Print(Base<T>& Object)
{
std::cout << Object.ToStringInterface() << std::endl;
}
这篇关于CRTP的静态多态性:使用基类调用派生方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!