-1

cppreference.com states that static_assert needs to be supplied a constexpr value of type bool. And that the method std::optional::operator bool() is declared constexpr.

This actually is about std::optional as function parameter. Imagine the following:

class T {
public:
    virtual void f(std::optional<int> i) {...};
};
class U : public T {
public:
    virtual void f(std::optional<int> i) override {
        static_assert(i, "This is no longer optional");
        f(i.value());
    }
    virtual void f(int i) {...}
};

The parameter that was optional in the base class transformed to a required parameter.
It is perfectly clear to me that this form of problem originates in bad OO-design, but I can't be asked to refactor it just now. I'll do that some point later (I promise :D). But I'd like to insert a quick compiler check.

My compiler tells me that:

[There is a] non-constant condition for static assertion

Why is this considered non-const?

Martin B.
  • 1,567
  • 14
  • 26

2 Answers2

1

First, parameters to functions, even parameters to constexpr functions, are never constexpr. You can only pass a constexpr value via a template parameter.

So this has nothing to do with optional.

Second, even if functions were allowed to take constexpr parameters, virtual functions would certainly not be able to do so. They rely on dynamic, runtime dispatch, so compile-time checking within the function is impossible.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
0

There is a really simple answer: i is not constexpr because i is a function argument (which is never constexpr unless in a compile-time call for a constexpr function, which is not the case.

Massa
  • 8,647
  • 2
  • 25
  • 26