作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试过实现一个列表容器,并决定移动一些通用功能像 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
等等都是纯虚拟的。所以基本上 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/
我是一名优秀的程序员,十分优秀!