我有两个类 A
和 B
,如下所示,B
必须继承自 A
。 B
类的classType()
函数没有提供,如果调用B::classType()
,会得到的类类型>一个
。我想在这里得到一个编译器错误,而不是调用 A
类的 classType()
函数。我该怎么做?
一般来说,A
的子类应该提供函数classType()
,以防作者忘记写classType()
函数,最好报编译错误。这就是目的。也许,我可以在 TypeOf()
函数中使用 static_assert
。
class A
{
public:
static const char* classType()
{
static const char* s_classType = "A";
return s_classType;
}
};
class B : public A
{
};
template <class T>
const char* TypeOf()
{
return T::classType();
}
int main()
{
const char* type = TypeOf<B>(); // I would like to get compiler error here, not get "A".
}
最佳答案
或者,在 B
中将 A::classType()
设为私有(private):
class B : public A {
private:
using A::classType;
}
编辑。问题弄清楚后,我建议您使用类型特征技术而不是静态成员函数。
template<class>
struct Traits;
template<>
struct Traits<A> {
static const char* classType() {
return "A";
}
};
template<class T>
const char* TypeOf() {
return Traits<T>::classType();
}
现在用户必须为B
定义自己的类型特征,否则
const char* type = TypeOf<B>();
不会编译。
关于c++ - 如何避免在基类中调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53323485/