gpt4 book ai didi

C++:什么是 Curiously-Recurring-Template-Pattern? Curiously-Recurring-Template-Pattern 可以替代虚函数吗?

转载 作者:可可西里 更新时间:2023-11-01 16:26:17 25 4
gpt4 key购买 nike

我没有对问题的准确描述,所以我只是想问一下这是否可能(如果可能的话,一些其他信息会很好)。

一位程序员告诉我,您可以避免由虚函数/多态性引起的运行时开销。他说,为了避免运行时开销,您可以在名为 Curiously_recurring_template_pattern 的模式中使用模板,它看起来像这样:

class Derived : public Base<Derived>
{
// ... implementation here
};

这个 Curiously-Recurring-Template-Pattern 是如何工作的?

如何使用 Curiously-Recurring-Template-Pattern 来替代普通的虚函数/多态性?

我是不是听错了?

最佳答案

非常具体地说,可以使用 CRTP 代替具有虚函数的基类来实现 template method pattern没有虚函数调用开销。

对于虚函数,TMP 看起来像这样:

class ProvidesMethod {
protected:
void Method() {
// do something
Part1();
// do something else
Part2();
// do something final
}

private:
virtual void Part1() = 0;
virtual void Part2() = 0;
};

class ExposesMethod : private ProvidesMethod {
public:
using ProvidesMethod::Method;

private:
void Part1() {
// first part implementation
}
void Part2() {
// second part implementation
}
};

对于 CRTP,它看起来像这样:

template <typename Derived>
class ProvidesMethod {
protected:
void Method() {
// do something
self().Part1();
// do something else
self().Part2();
// do something final
}

private:
Derived& self() { return *static_cast<Derived*>(this); }
const Derived& self() const { return *static_cast<const Derived*>(this); }
};

class ExposesMethod : private ProvidesMethod<ExposesMethod> {
public:
using ProvidesMethod<ExposesMethod>::Method;

private:
friend class ProvidesMethod<ExposesMethod>;
void Part1() {
// first part implementation
}
void Part2() {
// second part implementation
}
};

关于C++:什么是 Curiously-Recurring-Template-Pattern? Curiously-Recurring-Template-Pattern 可以替代虚函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16988450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com