相关疑难解决方法(0)

虚函数可以是constexpr吗?

可以X::f()在下面的代码中使用虚函数

struct X 
{
    constexpr virtual int f() const 
    {
        return 0;
    }
};
Run Code Online (Sandbox Code Playgroud)

constexpr吗?

c++ virtual-functions constexpr c++11

15
推荐指数
3
解决办法
5175
查看次数

constexpr和虚拟

我一直在想为什么constexrvirtual互相排斥,有人补充道:

... 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)

c++ c++11

8
推荐指数
1
解决办法
1063
查看次数

标签 统计

c++ ×2

c++11 ×2

constexpr ×1

virtual-functions ×1