Tom de Geus
Tom de Geus

Reputation: 5965

CRTP: use static constexpr from derived class

My CRTP derived class has some compile-time fixed dimension that I define using a static constexpr. Now I want to use it as a static variable from the base class. How do I do this?

Example:

#include <array>

template <class D>
class Base
{
public:
    void myfunc()
    {
        auto n = derived_cast().n;
        std::array<size_t, n> a;
    }

private:
    auto derived_cast() -> D&
    {
        return *static_cast<D*>(this);
    }

    auto derived_cast() const -> const D&
    {
        return *static_cast<const D*>(this);
    }
};

class A : public Base<A>
{
public:
    A() = default;

private:
    friend class Base<A>;
    static constexpr size_t n = 2;
};


int main()
{
    A a;
    a.myfunc();

    return 0;
}

This fails with:

error: non-type template argument is not a constant expression
        std::array<size_t, n> a;
                           ^

I also thought about using

std::array<size_t, derived_cast().n> a;

but that fails with:

error: non-type template argument is not a constant expression
        std::array<size_t, derived_cast().n> a;
                           ^~~~~~~~~~~~~~~~

So what should I put?

Upvotes: 0

Views: 452

Answers (2)

Maxim Eryomenko
Maxim Eryomenko

Reputation: 61

std::array<size_t, D::n> 

Upvotes: 2

Jarod42
Jarod42

Reputation: 217448

auto n = derived_cast().n; should be:

constexpr auto n = D::n;

Demo

Upvotes: 2

Related Questions