const模板参数在创建后不会保留常量

时间:2016-10-27 08:06:16

标签: c++ templates const

在第一次实例化后,为什么width不保留const

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;

它给出错误: 错误C2975&#39; N&#39;:&lt; ProjectionTest&#39;的无效模板参数,预期编译时常量表达式

1 个答案:

答案 0 :(得分:4)

非静态成员width是常量,但不是模板参数所需的编译时常量。

您可以使用constexpr(必须是静态成员),例如

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;

};

然后

ProjectionTest<int, test.width> test2;

LIVE with VC