Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integral template parameter. error: use of 'this' in a constant expression

Tags:

c++

I tried to find a similar answered question in SO but without success. Question is why it is considered as error to use at compile time known at compile time value of template parameter of known at compile time type? Common sense tells me, that this code can be OK. What is wrong in this case? Thanks!

#include <array>

using Cont = std::array<int, 2>;

class A
{
    Cont a_ = {};

public:
    int& at(bool first)
    {
        static_assert(sizeof(a_) / sizeof(int) == 2); // OK
        static_assert(a_.size() > 1); // error: non-constant condition for static assertion. error: use of 'this' in a constant expression
        return a_[first ? 0 : 1];
    }
};

at compiler explorer

UPDATE: it looks like dublicate but may be not because in the question under link the speech is about run-time evaluation, but here looks like a_.size() can be evaluated in compile-time.

UPDATE2 More clear example (after considering answers and comments)

#include <array>

using Cont = std::array<int, 2>;

// OK
void checkSize(const Cont& b)
{
    static_assert(b.size() == 2);
}

class A
{
    Cont a_ = {};

public:
    constexpr void checkSize() const
    {
        Cont b = {};
        static_assert(b.size() == 2); // OK
        static_assert(sizeof(a_) / sizeof(int) == 2); // OK
        static_assert(a_.size() == 2); // error: non-constant condition for static assertion. error: use of 'this' in a constant expression
    }
};

shows that the problem in this is involved to evaluate a_.size(). But why it is needed there, while a_ is known by compiler as non-virtual type and size() can be evaluated in compile time, may be is another question, so I'll check first answer.

like image 592
wtom Avatar asked Nov 16 '25 19:11

wtom


1 Answers

std::array::size, even though a constexpr function, isn't a static function. This means it requires an object instance to be invoked.

In this particular case, at isn't constexpr, therefore this isn't either and in turn _a. Since _a isn't constexpr, the result of _a.size() isn't constexpr too.

† Even if it is, the body still isn't considered constexpr.

like image 86
Passer By Avatar answered Nov 18 '25 09:11

Passer By



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!