gpt4 book ai didi

c++ - 编译时纯虚函数

转载 作者:行者123 更新时间:2023-11-28 06:12:38 27 4
gpt4 key购买 nike

我试过实现一个列表容器,并决定移动一些通用功能像 sum() 到基类,这样我就可以稍后在其他容器中重用它们。

所有的基础支撑类需要三个方法 empty()head()tail。我不能让那些纯虚拟因为支持类永远不会被实例化。但它仍然必须使用这些方法来实现自己的sum() 等方法。

我试过这样的:

#include <iostream>
using namespace std;

template<typename T>
class StatsSupport {
public:
T sum(void) const {
if (empty()) {
return T(0);
} else {
return head() + tail()->sum;
}
}

// other methods
};

template<typename T>
class List : public StatsSupport<T> {
public:
// constructors etc.

bool empty(void) const {return head_ != NULL;}
const T& head(void) const {return *head_;}
const List<T>& tail(void) const {return *tail_;}

// other methods
private:
T* head_;
List<T> *tail_;
};

但尝试使用 sum() 时出现编译错误

prog.cpp:8:13: error: there are no arguments to 'empty' that depend on a template parameter, so a declaration of 'empty' must be available [-fpermissive]
if (empty()) {
^

对于每个 empty()head()tail()

有什么建议吗?

最佳答案

问题是 StatsSupport找不到 empty , head等功能,因为这些既不存在于它也不存在于全局范围内。 StatsSupport不知道派生类中存在的函数。

基本上有两种方法可以解决这个问题:

  • 运行时多态性,您将虚拟析构函数添加到 StatsSupport并为 empty 添加声明, head等等都是纯虚拟的。
  • 通过使用 CRTP 编译时间多态性如评论中所述。我将重点关注后者。

所以基本上 StatsSupport需要找到一种方法来访问派生类的函数。这可以通过将派生类的类型添加为模板参数来完成,称为 CRTP :

template<class Derived, typename T>
class StatsSupport {
public:
T sum(void) const {
if (derived()->empty()) {
return T(0);
} else {
return derived()->head() + derived()->tail()->sum;
}
}

// other methods
private:
Derived *derived()
{
return static_cast<Derived*>(this);
}
const Derived *derived() const
{
return static_cast<const Derived*>(this);
}
};

template<typename T>
class List : public StatsSupport<List<T>, T> { // with some changes could be simplified to StatsSupport<List<T>> but this it ouf of scope of this question

我正在为 derived 使用函数而不是成员来保持类 const 的正确性。

当然,另一种选择是依赖于算法的不同设计。你在那里移动sum以及 StatsSupport 的所有其他功能进入全局命名空间,然后像 sum(my_container_instance) 一样访问它们.一种更像 STL 的方法是使用迭代器。然后你可以使用 std::accumulate 进行求和。

关于c++ - 编译时纯虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30952592/

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