Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use C++ non-template type parameters

Shulou Source: shulou.com Published: 2022-06-02 02:11:36 10月01日 Update

This article introduces the relevant knowledge of "how to use C++ non-template type parameters". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. non-template type parameters

Classification:

Template parameter classification type shape participates in non-type parameter

Concept:

1. Type parameter:

Appears in the template parameter list, followed by parameter type names such as class or typename

two。 Non-type parameter:

Use a constant as a parameter of the class (function) template, which can be used as a constant in the class (function) template.

Example:

Namespace cole {/ / defines a static array of template type template class array {public: t & operator [] (size_t index) {return _ array [index] } const T & operator [] (size_t index) const {return _ array [index];} size_t size () const {return _ size } bool empty () const {return 0 = = _ size;} private: t _ array [N]; size_t _ size;};}

Note:

1. Floating point numbers, class objects, and strings are not allowed as untyped template parameters

two。 Untyped template parameters must be able to confirm the results at compile time

2. Template specialization

Concept:

Some type-independent code can be implemented by using templates, but some wrong results may be obtained for some special types.

Example:

Templatebool IsEqual (const T & left,const T & right) {return left = = right;} / / specialization of function templates (for some types of specialization) / / bool IsEqual (const char* const & left,const char* const & right) bool IsEqual (const char* left,const char* right) {return strcmp (left, right) = = 0;} int main () {cout

Tags: Templates specializations parameters types functions compilers versions examples files special pointers code foundations concepts results errors two formal parameters centering brackets Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft MariaDB macOS Shulou Technology Xiaomi