假设我有提供一些虚拟方法的类。某些功能不是强制性要重写的,但是我需要确保,如果类重写了特定方法,那么与第一个方法有关的第二个方法也必须被重写。
这是一些代码来解释这一点:
struct Base {
virtual void f();
virtual void g();
};
struct Good1 : Base {
void f() override;
void g() override;
};
struct Good2 : Base {
};
struct Bad1 : Base {
void f() override;
};
struct Bad2 : Base {
void g() override;
};
我希望Good
类可以编译,而不是Bad
类。这可能吗?
最佳答案
您可以使用static_assert产生编译时错误,并使用CRTP + typeinfo来检测是否重写了所有方法或没有方法。
#include <typeinfo>
template <typename B, typename T> constexpr bool are_both_overriden(){
return ((std::is_same<decltype(&B::f),decltype(&T::f)>::value && std::is_same<decltype(&B::g),decltype(&T::g)>::value)
|| (!std::is_same<decltype(&B::f),decltype(&T::f)>::value && !std::is_same<decltype(&B::g),decltype(&T::g)>::value));
}
template <typename D>
struct Base
{
virtual void f() {}
virtual void g() {}
Base(){
static_assert (are_both_overriden<Base, D>(), "Base requires all or none methods overriden");
}
};
struct Good1 : Base<Good1> {
void f() override{
}
void g() override{
}
};
struct Good1 : Base<Good1> {
};
struct Bad1 : Base<Bad1> {
void f() override{
}
};//WILL PRODUCE COMPILER ERROR
struct Bad1 : Base<Bad1> {
void g() override{
}
};//WILL PRODUCE COMPILER ERROR
关于c++ - 我可以强制子类重写这两个函数,还是都不重写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64175474/