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

查看:207
本文介绍了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?

这是问题的后续这里。我特别想要解决如果有一个差异WRT变量声明为函数或模板的extern const int?

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?

推荐答案

以下是来自标准。


非类型非模板模板参数的模板参数应为以下形式之一:

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


  • 整数或枚举类型的积分常数表达式;或

  • 非类型模板参数的名称;或

  • 具有外部链接的对象或函数的地址,包括函数模板和函数模板id,但不包括非静态类成员,表示为& id-expression其中&是可选的,如果名称引用一个函数或数组,或者如果相应的模板参数是引用;

5.19.1:


在多个地方,C ++需要求值为整数或枚举常量的表达式: (8.3.4,5.3.4),作为情况表达式(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)只有在转换为整数或枚举类型时才会出现。只能键入转换为积分或枚举类型
tion类型。特别是,除非在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 ... 初始化与... 't认为初始化外部计数)。

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天全站免登陆