gjohnson gjohnson - 1 month ago 12
C++ Question

const template parameter does not retain const-ness after creation

Why doesn't

width
retain its
const
ness 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

Answer

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

Comments