【发布时间】:2014-01-28 10:07:10
【问题描述】:
我有一堆类(我从不实例化)以不同的方式实现相同的静态内联方法。我试图了解这些班级是否可以有一个共同的父母。 目的不是进行虚拟调用,而只是为想要以不同方式再次编写实现该方法的新类的任何人强制一个结构。我可以这样做吗?我开始认为这不是 C++ 提供的一种功能。
class XXX {
public:
///Should force any derived class to implement
///bool compute(const unsigned char i1, const unsigned char i2);
};
class GreaterThan : public XXX {
public:
static inline bool compute(const unsigned char i1, const unsigned char i2) {
return i1 > i2;
}
};
class NotGreaterThan : public XXX {
public:
static inline bool compute(const unsigned char i1, const unsigned char i2) {
return i1 <= i2;
}
};
class NotLessThan : public XXX { ///This should not compile
public:
static inline bool compute2(const unsigned char i1, const unsigned char i2) {
return i1 >= i2;
}
};
[...]
在基类中定义纯虚方法compute 不允许我在派生类中定义静态方法。当我将它用作仿函数时,让方法不是静态的会迫使我实例化该类,并且基本上会阻止内联。
注意:here 提出了类似的问题。
编辑:可能,这也不应该编译:
class LessThan : public XXX { ///Also this should not compile
public:
static inline bool compute(const float i1, const float i2) {
return i1 < i2;
}
};
【问题讨论】:
标签: c++ static-methods