简体   繁体   中英

Implicitly virtual constexpr function

Virtual functions cannot be constexpr however, when a function is implicitly virtual through inheritance, the compilers I have tried don't complain about it.

Here is a sample code:

class A
{
    virtual void doSomething() {}
};

class B : public A
{
    constexpr void doSomething() override {} // implicitly virtual constexpr
                                             // but no compilation error
};

class C : public A
{
    virtual constexpr void doSomething() override {} // explicitly virtual constexpr
                                                     // compilation error
};

I tried it with gcc 7.2.0 and clang 5.0.0 .

Are those compilers not compliant to the standard in this regard, or are implicitly virtual constexpr functions allowed ?

The compilers have a bug. Note that this has been fixed in clang 3.5 already, not sure why you don't get an error, because I do.

The standard is pretty explicit about this in [dcl.constexpr]p3 :

The definition of a constexpr function shall satisfy the following requirements:

  • it shall not be virtual;
  • [...]

It does't matter whether doSomething is implicitly virtual or not. In both cases, it is considered to be virtual , and so it violates the point above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM