来自基础 ctor 的纯虚拟"very const"函数调用



我知道禁止从基元调用虚拟函数,这是有原因的。但是如果函数是";非常常量";,我认为,这些原因变得无关紧要"非常常量"意味着函数是常数的直接替换,如下所示:

Color Derived::getColor() const
{
return Color(0, 255, 0); // no member usage, no member function calls -
// only return
}

(我使用函数是因为我需要它的虚拟性。(我能告诉编译器这个函数是";非常const";?(它将允许我从ctor调用这个函数。(

如果从基类构造函数调用虚拟方法,将获得基类方法,而不是任何重写的方法。

(实际上,根据具体情况,这可能是未定义的行为,但这是通常的实际效果(。

可能不是最简单的解决方案,但CRTP可以帮助解决此类问题。。。

template <typename Derived>
struct Base {
Base() {
c = getColor();
}
int getColor() const {
return static_cast<const Derived&>(*this).getColor();
}
int c;
};
struct D1 : Base<D1> {
int getColor() const {
return 1;
}
};
struct D2 : Base<D2> {
int getColor() const {
return 2;
}
};

最新更新