【问题标题】:const template parameter does not retain const-ness after creationconst 模板参数在创建后不保留 const-ness
【发布时间】:2016-10-27 08:06:16
【问题描述】:

为什么width 在第一次实例化后不保留其constness?

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“N”:“ProjectionTest”的模板参数无效,预期的编译时常量表达式

【问题讨论】:

  • 为此使用constexpr。或static const
  • 我试过 constexpr,它给出了错误 C2126 'ProjectionTest::width' 不能用 'constexpr' 说明符声明。没有尝试静态常量,但它给出了错误 C2438 'width': cannot initialize static class data via constructor
  • 错误,它必须是static constexpr。你定义的是一个非静态成员,

标签: c++ templates constants


【解决方案1】:

非静态成员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

【讨论】:

  • 请注意,您必须使其成为静态成员
  • 谢谢你的工作。我认为宽度会在不同宽度的实例中保持其值(因为它是静态的),但事实并非如此。
  • @gjohnson 不,每个具有不同模板参数的实例化模板类都是无关紧要的。所以,ProjectionTest&lt;int, 9&gt;::widthProjectionTest&lt;int, 7&gt;::width 是两个独立的东西。
猜你喜欢
  • 2011-04-10
  • 2017-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-10
  • 2010-11-01
  • 1970-01-01
相关资源
最近更新 更多