【问题标题】:Why can't template non type parameters be of class type为什么模板非类型参数不能是类类型
【发布时间】:2010-11-05 07:30:11
【问题描述】:
class Example {

   // ...
};

template <typename T, Example ex>  //Error
class MyExample{

   // ...
};

我的问题是为什么模板非类型参数不能是类类型?

我得到的错误是

error: ‘class Example’ is not a valid type for a template constant parameter

【问题讨论】:

  • 请澄清——你看到什么样的编译器错误?
  • 尝试(示例 * ex)。它会起作用的:]
  • 也许(示例和前)有效。试试看嘛 。 . .
  • 应该有效!因为“——引用对象或引用函数”

标签: c++ templates types


【解决方案1】:

很简单,因为这些是规则。合理地,必须在编译时解析模板参数,并且仅在运行时构造类类型的对象(即使是临时对象和具有静态存储持续时间的对象)。您只能拥有在编译时可解析的“值”模板参数,例如整数和类型。不过,模板参数可以是对象的指针或引用。

【讨论】:

    【解决方案2】:

    根据c++ standard

    A non-type template-parameter shall have one of the following (optionally cv-qualified) types:
    — integral or enumeration type,
    — pointer to object or pointer to function,
    — reference to object or reference to function,
    — pointer to member.
    
    A non-type template-parameter shall not be declared to have floating point, **class**, or void type. 
    

    很明显,如果将类声明为非类型模板参数,任何符合标准的编译器都会抛出错误。

    【讨论】:

      【解决方案3】:

      从 C++ 20 开始,现在是 supported

      类一般需要是Literal Type

      【讨论】:

      • 真的吗?它在幕后是如何运作的?
      • @JensB 我不知道实现的实际工作方式,但我猜类成员是序列化的,并且在名称修饰中使用。所以在概念上类似于(真的)宽整数。但是有一些限制:该类必须是Literal Type,这意味着例如所有相关的东西都需要是constexpr。如果您阅读了 LiteralType 的要求,它会确保这种序列化实际上是可能的,并且它们确实表现得像(编译时)常量对象应该表现的那样。
      • @JensB 这是一个非常酷的功能,甚至可以与auto 结合使用:-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 2011-08-06
      相关资源
      最近更新 更多