C++模板参数有什么要求? [英] What are the requirements for C++ template parameters?

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

问题描述

如果您在 C++ 中使用将整数值作为参数的模板,那么对于用作参数的整数变量是否与在函数调用中用作参数的情况有所不同?

If you are using a template in C++ that takes an integer value as a parameter, are there any requirements on an integer variable used as the parameter that are different than if the variable was used as a parameter in a function call?

这是问题这里的后续 .我特别想解决在函数或模板中声明为extern const int"的 WRT 变量是否存在差异?

This is a follow-up to question here . I specifically want to address if there is a difference WRT variables declared as "extern const int" for functions or templates?

我可以看到,对于某些模板情况,编译时需要参数值.这总是真的吗?有没有办法指定(可能仅用于参数值的某些用途)在运行时使用该值?

I can see that for some template cases the parameter value would be needed at compile time. Is this always true? Is there a way to specify, maybe for only certain uses of the parameter value, that the value be used at runtime?

推荐答案

以下内容来自标准.

14.3.2.1:

非类型、非模板模板参数的模板参数应为:

A template-argument for a non-type, non-template template-parameter shall be one of:

  • 整数或枚举类型的整数常量表达式;或
  • 非类型模板参数的名称;或
  • 具有外部链接的对象或函数的地址,包括函数模板和函数模板ID,但不包括非静态类成员,表示为 &id 表达式,其中 &如果名称引用函数或数组,或者相应的模板参数是引用,则是可选的;或
  • 指向成员的指针,如 5.3.1 中所述.

5.19.1:

在一些地方,C++ 需要计算为整数或枚举常量的表达式:作为数组边界 (8.3.4, 5.3.4),作为 case 表达式 (6.4.2),作为位域长度 (9.6),作为枚举初始化器 (7.2)、作为静态成员初始化器 (9.4.2) 以及作为整数或枚举非类型模板参数 (14.3).

In several places, C++ requires expressions that evaluate to an integral or enumeration constant: as array bounds (8.3.4, 5.3.4), as case expressions (6.4.2), as bit-field lengths (9.6), as enumerator initializers (7.2), as static member initializers (9.4.2), and as integral or enumeration non-type template arguments (14.3).

 constant-expression:
            conditional-expression

整型常量表达式只能涉及文字 (2.13)、枚举数、常量变量或使用常量表达式 (8.5) 初始化的整型或枚举类型的静态数据成员、整型或枚举类型的非类型模板参数和 sizeof表达式.浮动文字 (2.13.3) 仅在它们被强制转换为整数或枚举类型时才能出现.仅类型转换为整数或枚举-可以使用类型.特别是,除了 sizeof 表达式外,不得使用函数、类对象、指针或引用,不得使用赋值、递增、递减、函数调用或逗号运算符.

An integral constant-expression can involve only literals (2.13), enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions (8.5), non-type template parameters of integral or enumeration types, and sizeof expressions. Floating literals (2.13.3) can appear only if they are cast to integral or enumeration types. Only type conversions to integral or enumera- tion types can be used. In particular, except in sizeof expressions, functions, class objects, pointers, or references shall not be used, and assignment, increment, decrement, function-call, or comma operators shall not be used.

关于您之前的帖子,我相信const variables ... initialised with ..."部分的本质(我认为外部初始化并不重要).

With respect to your previous post I believe the essence in the part "const variables ... initialised with ..." (and I don't think initialised externally counts).

这篇关于C++模板参数有什么要求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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