C++ CRTP 类层次结构
来自维基百科:
// The Curiously Recurring Template Pattern (CRTP)
template <typename T>
struct base
{
// ...
};
struct derived : base<derived>
{
// ...
};
现在如果我想要衍生自_衍生
,我可以写:
// The Curiously Recurring Template Pattern (CRTP)
template <typename T>
struct base
{
// ...
};
template <typename T>
struct derived : base<T>
{
// ...
};
struct derived_from_derived : derived <derived_from_derived>
{
// ...
};
现在假设我只想要一个派生
对象。这是行不通的:
derived<derived> obj;
衍生
必须是抽象的,还是有办法实例化它?
From Wikipedia:
// The Curiously Recurring Template Pattern (CRTP)
template <typename T>
struct base
{
// ...
};
struct derived : base<derived>
{
// ...
};
Now if I want derived_from_derived
, I can write:
// The Curiously Recurring Template Pattern (CRTP)
template <typename T>
struct base
{
// ...
};
template <typename T>
struct derived : base<T>
{
// ...
};
struct derived_from_derived : derived <derived_from_derived>
{
// ...
};
Now suppose I just want a derived
object. This doesn't work:
derived<derived> obj;
Does derived
have to be abstract, or is there a way to instantiate it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我自己的答案是这样的:
现在我可以有一个
衍生::类型<>;对象
。此外,参数化继承也有效(例如装饰器模式):My own answer is this:
Now I can have a
derived::type<> obj
. Also, parametized inheritance works (e.g. decorator pattern):CRTP 对更深继承层次结构的支持通常是通过在继承层次结构中您自己的类之间“插入”CRTP 类来实现的:
Support for deeper inheritance hierarchies with CRTP usually is implemented by "inserting" CRTP classes between your own classes in the inheritance hierarchy:
这样做是不合法的,因为内部派生不是一个类,而是它本身是一个模板,而不是派生模板的合法参数。
通常完成此操作的方法是拥有一组派生模板实现,然后每个实现都有一个单独的类,用于将该实现实例化为具体类。
It's not legal to do that, since the inner derived is not a class, but is itself a template, and not a legal argument for the derived template.
The way that this is usually done is to have a set of derived templates implementations, and then each implementation has a separate class which is used to instantiate that implementation as a concrete class.
不允许,因为
衍生
是一个模板
类,并且内部衍生
尚未完成。它需要具有类似于衍生
的类型。is not allowed because
derived
is atemplate
class and the innerderived
is not yet complete. It needs to have a type likederived<int>
.不存在“仅”派生对象之类的东西,就像您不能“仅”
std::vector
一样,也不可能具有float x = sqrt();
。该类型需要一个参数,并且您必须提供它。There's no such thing as "just" a derived object, just like you cannot have "just"
std::vector
, nor can you havefloat x = sqrt();
. The type requires an argument, and you must provide it.