非类型模板参数 [英] Non-type template parameters

查看:78
本文介绍了非类型模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道非类型模板参数应该是一个常数整数表达式。有人可以弄清楚为什么会这样吗?

I understand that the non-type template parameter should be a constant integral expression. Can someone shed light why is it so ?

template <std::string temp>
void foo()
{
     // ...
}




error C2993: 'std::string' : illegal type for non-type template parameter 'temp'.


我知道什么是常数积分表达式。不允许使用上述代码段中的 std :: string 这样的非常量类型的原因是什么?

I understand what a constant integral expression is. What are the reasons for not allowing non-constant types like std::string as in the above snippet ?

推荐答案

之所以不能这样做,是因为在编译期间无法解析和替换非常量表达式。它们可能会在运行时更改,这将需要在运行时生成新模板,这是不可能的,因为模板是编译时的概念。

The reason you can't do this is because non-constant expressions can't be parsed and substituted during compile-time. They could change during runtime, which would require the generation of a new template during runtime, which isn't possible because templates are a compile-time concept.

以下是该标准允许的非类型模板参数(14.1 [temp.param] p4):

Here's what the standard allows for non-type template parameters (14.1 [temp.param] p4):


非类型模板参数应具有以下值之一(可选为cv限定) )类型:

A non-type template-parameter shall have one of the following (optionally cv-qualified) types:


  • 整数或枚举类型,

  • 指向对象或函数的指针,

  • 对对象的左值引用或对函数的左值引用,

  • 指向成员的指针,

  • std: :nullptr_t

  • integral or enumeration type,
  • pointer to object or pointer to function,
  • lvalue reference to object or lvalue reference to function,
  • pointer to member,
  • std::nullptr_t.

这篇关于非类型模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆