The program does not work if I declare the class as const ... and not constexpr?

Here is my program:

#include <iostream>

class Debug {
public:
    constexpr Debug(bool h): hw(h){}
    constexpr bool any() { return hw; }
private:
    bool hw;
};

int main(){

    const Debug x(true);

    constexpr bool f = x.any();

}

This results in the error "value" x "is not used in constant expression". If I replaced

const Debug x(true);

with

constexpr Debug x(true);

Then everything works fine. I was impressed with the placement of constexpr before the definition of the object was synonymous with “implicitly making this variable a constant when checking its constant expression variable”. This would suggest to me that instead of the const constant there should be nothing else in the case of this program. In fact, if something was to make a mistake, it should declare it as "constexpr", and not as "const".

, . , x . Debug , x const constexpr , .

: ( , ).

using namespace std;

class Debug {
public:
    constexpr Debug(bool h): hw(h){}
private:
    bool hw;
};

int main(){
    const Debug x(true);
    constexpr Debug f = x;
}
+4
1

constexpr, , , , . - , .

So x.any() , x - constexpr. const, x.any() .

+4

All Articles