What are the requirements for C++ template parameters?

后端 未结 3 1802
無奈伤痛
無奈伤痛 2020-12-09 22:10

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 tha

3条回答
  •  旧时难觅i
    2020-12-09 22:24

    The following is from the standard.

    14.3.2.1:

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

    • an integral constant-expression of integral or enumeration type; or
    • the name of a non-type template-parameter; or
    • the address of an object or function with external linkage, including function templates and function template-ids but excluding non-static class members, expressed as & id-expression where the & is optional if the name refers to a function or array, or if the corresponding template-parameter is a reference; or
    • a pointer to member expressed as described in 5.3.1 .

    5.19.1:

    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
    

    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.

    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).

提交回复
热议问题