gjohnson
gjohnson

Reputation: 49

const template parameter does not retain const-ness after creation

Why doesn't width retain its constness after the first instantiation?

template<typename T, const std::size_t N>
class ProjectionTest
{
    std::array<T, N*N> _arr;
public:
    ProjectionTest() : width(N)
    { }

    const std::size_t width = 0;

};

ProjectionTest<int, 9> test;
ProjectionTest<int, test.width> test2;

It gives error: Error C2975 'N': invalid template argument for 'ProjectionTest', expected compile-time constant expression

Upvotes: 1

Views: 237

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

The non-static member width is constant, but not compile-time constant, which is needed for template argument.

You could use constexpr (which has to be static member), e.g.

template<typename T, const std::size_t N>
class ProjectionTest
{
    std::array<T, N*N> _arr;
public:
    ProjectionTest()
    { }

    constexpr static std::size_t width = N;

};

then

ProjectionTest<int, test.width> test2;

LIVE with VC

Upvotes: 4

Related Questions