可以X::f()在下面的代码中使用虚函数
struct X
{
constexpr virtual int f() const
{
return 0;
}
};
Run Code Online (Sandbox Code Playgroud)
是constexpr吗?
我一直在想为什么constexr和virtual互相排斥,有人补充道:
... constexpr是关于编译时的执行; 如果我们在编译时执行该函数,我们显然也知道它在编译时所处理的数据类型,因此后期绑定显然不相关.
但是,即使在编译时,动态类型也可能与静态类型不同,并且可能存在需要动态类型的情况:
class A {
public:
/* virtual */ constexpr int foo() {
return 1;
}
};
class B : public A {
public:
constexpr int foo() {
return 2;
}
};
constexpr int foo(A &a) {
// The static type is fixed here.
// What if we want to call B::foo() ?
return a.foo();
}
int main() {
B b;
constexpr int c = foo(b);
return …Run Code Online (Sandbox Code Playgroud)