Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicitly virtual constexpr function

Tags:

c++

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 ?

like image 882
MaxV37 Avatar asked Oct 11 '17 19:10

MaxV37


People also ask

Can constexpr functions be virtual?

Can virtual functions be constexpr? Yes. Only since C++20, virtual functions can be constexpr .

Is constexpr implicitly static?

constexpr functions are implicitly inline , but not implicitly static .

What is the function of constexpr?

A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations. And when a value is computed at compile time instead of run time, it helps your program run faster and use less memory.

Is constexpr implicitly const?

In C++11, constexpr member functions are implicitly const.


1 Answers

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.

like image 63
Rakete1111 Avatar answered Nov 13 '22 18:11

Rakete1111