什么才是真正的情人| 吃什么可以软化血管| 胃下垂有什么症状表现| 踏雪寻梅是什么意思| 吃什么补肺| 蝉的幼虫叫什么| 地瓜不能和什么一起吃| 蜂蜡有什么用| fe是什么元素| 马齿苋长什么样子| 包皮炎挂什么科| 哼哈二将是什么意思| 涤纶是什么面料优缺点| 医院规培是什么意思| 付梓什么意思| 失信人是什么意思| 下雨天适合穿什么衣服| 潼字五行属什么| 最多笔画的汉字是什么| 心脏不舒服有什么症状| 西瓜什么时候传入中国| 三楼属于五行属什么| hscrp高是什么感染| glu是什么氨基酸| aba是什么意思| 什么是公元前和公元后| 矜贵是什么意思| 早餐做什么简单又好吃| 什么叫便溏| 925是什么意思| 眼前的苟且是什么意思| 牙齿松动是什么原因引起的| 人格分裂什么意思| 献出什么| 什么是职业病| 泪腺堵塞有什么症状| 做包皮手术有什么好处| 扎西德勒是什么意思| 虫草泡水喝有什么功效| 眉毛白是什么原因引起的| 为什么怀不上孕| 11月5号是什么星座| 圆谎是什么意思| lively是什么意思| 向心性肥胖是什么意思| 妊娠阴性是什么意思| 萤火虫为什么会发光| 梦见包丢了是什么意思| 小河虾吃什么| 忏悔什么意思| 赤小豆有什么作用| lalpina是什么牌子| 喝什么茶去湿气最好| 肠胃炎吃什么消炎药| 厅堂是什么意思| 子宫内膜增厚有什么影响| 大姨妈量少是什么原因| 3911农药主要治什么| 水奶和奶粉什么区别| 滑脉是什么意思| 杀跌是什么意思| 例假不能吃什么水果| 姜子牙姓什么| 16岁属什么| 姐姐的小孩叫什么| 今年是什么年庚| 口腔溃疡吃什么药好的快| 做胃镜前喝的那个液体是什么| ns是什么| 38年属什么生肖| 皮肤自愈能力差缺什么| bic是什么意思| 烂脚丫用什么药最好| 茶壶里煮饺子的歇后语是什么| 吃什么补气虚最快最好| 瘪嘴是什么意思| 登革热是什么病| 石钟乳是什么| 猫咪弓背是什么原因| 尼古丁是什么| 胃底腺息肉什么意思| 9月12是什么星座| 妮子什么意思| 天空像什么的比喻句| 泵的扬程什么意思| 国家穷为什么不多印钱| 流鼻涕吃什么药最管用| circles是什么意思| 神经官能症挂什么科| eb病毒igg抗体阳性是什么意思| 井泉水命什么意思| 桃子是什么形状| 强迫症吃什么药| 小苏打是什么成分| 鲁字五行属什么| 9月是什么星座| 生孩子送什么花比较好| 面霜和乳液有什么区别| 戴银镯子对身体有什么好处| 猫咪喜欢什么颜色| 头发干枯毛躁是什么原因| 寿者相什么意思| 口炎读什么| 多梦吃什么药效果最好| 阴阳什么意思| 女人高潮是什么感觉| poscer是什么牌子手表| 壬水代表什么| 分泌物过氧化氢阳性是什么意思| 什么叫人工智能| 子宫有积液是什么原因引起的| 脾胃气滞吃什么中成药| 土豆什么时候收获| 血脂高胆固醇高吃什么好| 足跟痛是什么原因| wing是什么意思| 做梦梦到蟒蛇是什么征兆| fruits是什么意思| 催经吃什么药| 衣冠禽兽是什么意思| 葛根有什么功效| 子宫内膜什么时候脱落| 姝字五行属什么的| 一键挪车什么意思| rh血型阳性是什么血型| 24k黄金是什么意思| 丛书是什么意思| 小蜘蛛吃什么| 阑尾炎挂号挂什么科| 木薯粉可以做什么美食| 吃东西恶心想吐是什么原因| 牙齿什么颜色最健康| 地球上什么东西每天要走的距离最远| 谷草谷丙比值偏高说明什么| 胺碘酮又叫什么名字| 乏力是什么意思| 沉香手串有什么好处| 今年78岁属什么生肖| 一心向阳下一句是什么| 什么的青蛙| 情人节送什么给女孩子| 祛湿有什么好处| 什么是邮箱地址| 1月29日是什么星座| 顶针什么意思| 男性尿很黄是什么原因| 高血压高血糖挂什么科| 漫字五行属什么| 二元酸是什么| 什么情况下容易怀孕| 梦见吃豆腐是什么意思| 暮雪是什么意思| 带状疱疹什么样子| 富字五行属什么| 血压什么时间测量最准| 为什么会肠鸣| 新生儿吐奶是什么原因| 美容师都要学什么| 巨石强森是什么人种| 什么路最窄打一生肖| 嘴炮是什么意思| 8月11日是什么星座| 喝枸杞子泡水有什么好处和坏处| 炖鸡汤放什么材料好吃| lch是什么病| eu是什么元素| pagani是什么车| 血糖仪什么牌子的好用又准确| 天堂是什么意思| 为什么13周不让建卡了| noon是什么意思| 夏至吃什么食物| 拉肚子喝什么粥| 什么挑担子忠心耿耿| 吃什么油最健康排行榜| 电解质氯高是什么原因| 势利眼的人有什么特征| 05年属什么| 广东有什么好玩的地方| 大利月小利月什么意思| 大鼻是什么生肖| 儿童抽动症挂什么科| 墨西哥用什么货币| 异什么同什么| 肌肉僵硬是什么原因引起的| 补肾吃什么药最好| 端午节在什么时候| 不明原因发烧挂什么科| 78年属什么生肖| 辟谣是什么意思| trust阴性tppa阳性说明什么| poppy是什么意思| 浑浑噩噩是什么意思| 胆固醇高有什么症状| 垒是什么意思| 甲状腺斑块是什么意思| 免疫组化是什么意思| 吴佳尼为什么嫁马景涛| 梦见吃雪糕是什么意思| 出汗多吃什么好| 1997属什么| 胃有幽门螺旋杆菌是什么症状| 心病是什么意思| 玥字五行属什么| 胸口闷是什么原因| 什么因果才会有双胞胎| 内分泌失调挂什么科| 什么叫野鸡大学| 嘴干嘴苦是什么原因| 病史是什么意思| 混社会的人一般干什么| cdf是什么意思| 女生体毛多是什么原因| 耳机戴久了有什么危害| 肠鸣吃什么药| 气血亏吃什么补的快| 燃面为什么叫燃面| 白细胞低是怎么回事有什么危害| ppm是什么单位| camp医学上是什么意思| 奶油小生什么意思| 阴虱有什么症状| 鼻炎什么症状| 节气是什么意思| mm是什么病| 膑是什么意思| 111是什么意思| 经常犯困是什么原因| 农历六月初十是什么日子| manu是什么意思| 小白脸是什么意思| 慢性咽喉炎什么症状| 为什么眼泪是咸的| 补充蛋白质吃什么最好| 什么动物会冬眠| 高温中暑吃什么药| 皮肤湿疹用什么药膏| 什么水果不能上供| 什么什么不什么| 火加同念什么| 房颤什么意思| 王一博是什么星座| 四大是什么| 猕猴桃是什么季节的水果| 仓鼠咬笼子是什么原因| 2015年五行属什么| 狗感冒吃什么药| 拔节是什么意思| 刘备的马叫什么名字| 海鸥手表是什么档次| 男生剪什么发型好看| 去心火喝什么茶好| 脸上长癣用什么药膏| 神经肌电图检查什么| 救人一命胜造七级浮屠是什么意思| 99属什么| 晒伤涂什么| 牙掉了是什么预兆| 儿童过敏性鼻炎吃什么药好| 为什么腿老是抽筋| 哗众取宠是什么意思| 8岁属什么| 1962年属什么生肖| 指责的意思是什么| 百度Jump to content

用车特殊路况特殊对待 你的车能顺利过去吗?

From Wikipedia, the free encyclopedia
(Redirected from Template (programming))
百度 另外,万一遇到突发情况,可自由控制的车速极有可能帮助驾驶员避险,毕竟生命比什么都重要。

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class declaration to reference via a generic variable another different class (built-in or newly declared data type) without creating full declaration for each of these different classes.

In plain terms, a templated class or function would be the equivalent of (before "compiling") copying and pasting the templated block of code where it is used, and then replacing the template parameter with the actual one. For this reason, classes employing templated methods place the implementation in the headers (*.h files) as no symbol could be compiled without knowing the type beforehand.

The C++ Standard Library provides many useful functions within a framework of connected templates.

Major inspirations for C++ templates were the parameterized modules provided by the language CLU and the generics provided by Ada.[1]

Technical overview

[edit]

There are three kinds of templates: function templates, class templates and, since C++14, variable templates. Since C++11, templates may be either variadic or non-variadic; in earlier versions of C++ they are always non-variadic.

C++ Templates are Turing complete.[2]

Function templates

[edit]

A function template behaves like a function except that the template can accept arguments of various types, enabling type-generic behavior (see example). In other words, a function template represents a family of functions. The format for declaring function templates with type parameters is:

template<class identifier> declaration;
template<typename identifier> declaration;

Both expressions have the same meaning and behave in exactly the same way. The latter form was introduced to avoid confusion,[3] since a type parameter need not be a class until C++20. (It can be a basic type such as int or double.)

For example, the C++ Standard Library contains the function template max(x, y) which returns the larger of x and y. That function template could be defined like this[4]:

template<class T>
const T& max(const T& a, const T& b)
{
    return a < b ? b : a;
}

This single function definition works with many data types. Specifically, it works with all data types for which < (the less-than operator) is defined and returns a value with a type convertible to bool. The usage of a function template saves space in the source code file in addition to limiting changes to one function description and making the code easier to read.

An instantiated function template usually produces the same object code, though, compared to writing separate functions for all the different data types used in a specific program. For example, if a program uses both an int and a double version of the max() function template above, the compiler will create an object code version of max() that operates on int arguments and another object code version that operates on double arguments.[citation needed] The compiler output will be identical to what would have been produced if the source code had contained two separate non-templated versions of max(), one written to handle int and one written to handle double.

Here is how the function template could be used:

#include <iostream>

int main() {
    // This will call max<int> by implicit argument deduction.
    std::cout << std::max(3, 7) << '\n';

    // This will call max<double> by implicit argument deduction.
    std::cout << std::max(3.0, 7.0) << '\n';

    // We need to explicitly specify the type of the arguments; 
    // although std::type_identity could solve this problem...
    std::cout << max<double>(3, 7.0) << '\n';
}

In the first two cases, the template argument T is automatically deduced by the compiler to be int and double, respectively. In the third case automatic deduction of max(3, 7.0) would fail because the type of the parameters must in general match the template arguments exactly. Therefore, we explicitly instantiate the double version with max<double>().

This function template can be instantiated with any copy-constructible type for which the expression y < x is valid. For user-defined types, this implies that the less-than operator (<) must be overloaded in the type.

Abbreviated function templates

[edit]

Since C++20, using auto or Concept auto in any of the parameters of a function declaration, that declaration becomes an abbreviated function template declaration.[5] Such a declaration declares a function template and one invented template parameter for each placeholder is appended to the template parameter list:

void f1(auto); // same as template<class T> void f1(T)
void f2(C1 auto); // same as template<C1 T> void f2(T), if C1 is a concept
void f3(C2 auto...); // same as template<C2... Ts> void f3(Ts...), if C2 is a concept
void f4(C2 auto, ...); // same as template<C2 T> void f4(T...), if C2 is a concept
void f5(const C3 auto*, C4 auto&); // same as template<C3 T, C4 U> void f5(const T*, U&);

Class templates

[edit]

A class template provides a specification for generating classes based on parameters. Class templates are generally used to implement containers. A class template is instantiated by passing a given set of types to it as template arguments.[6] The C++ Standard Library contains many class templates, in particular the containers adapted from the Standard Template Library, such as vector.

Variable templates

[edit]

In C++14, templates can be also used for variables, as in the following example:

template<typename T> 
constexpr T pi = T{3.141592653589793238462643383L}; // (Almost) from std::numbers::pi

Non-type template parameters

[edit]

Although templating on types, as in the examples above, is the most common form of templating in C++, it is also possible to template on values. Thus, for example, a class declared with

template <int K>
class MyClass;

can be instantiated with a specific int.

As a real-world example, the standard library fixed-size array type std::array is templated on both a type (representing the type of object that the array holds) and a number which is of type std::size_t (representing the number of elements the array holds). std::array can be declared as follows:

template<class T, size_t N> struct array;

and an array of six chars might be declared:

array<char, 6> myArray;

Template specialization

[edit]

When a function or class is instantiated from a template, a specialization of that template is created by the compiler for the set of arguments used, and the specialization is referred to as being a generated specialization.

Explicit template specialization

[edit]

Sometimes, the programmer may decide to implement a special version of a function (or class) for a given set of template type arguments which is called an explicit specialization. In this way certain template types can have a specialized implementation that is optimized for the type or a more meaningful implementation than the generic implementation.

  • If a class template is specialized by a subset of its parameters it is called partial template specialization (function templates cannot be partially specialized).
  • If all of the parameters are specialized it is a full specialization.

Explicit specialization is used when the behavior of a function or class for particular choices of the template parameters must deviate from the generic behavior: that is, from the code generated by the main template, or templates. For example, the template definition below defines a specific implementation of max() for arguments of type const char*:

#include <cstring>

template<> 
const char* max(const char* a, const char* b) {
    // Normally, the result of a direct comparison
    // between two C strings is undefined behaviour;
    // using std::strcmp makes defined.
    return std::strcmp(a, b) > 0 ? a : b;
}

Variadic templates

[edit]

C++11 introduced variadic templates, which can take a variable number of arguments in a manner somewhat similar to variadic functions such as std::printf.

Template aliases

[edit]

C++11 introduced template aliases, which act like parameterized typedefs.

The following code shows the definition of a template alias StrMap. This allows, for example, StrMap<int> to be used as shorthand for std::unordered_map<int,std::string>.

template<typename T> using StrMap = std::unordered_map<T, std::string>;

Generic programming features in other languages

[edit]

Initially, the concept of templates was not included in some languages, such as Java and C# 1.0. Java's adoption of generics mimics the behavior of templates, but is technically different. C# added generics (parameterized types) in .NET 2.0. The generics in Ada predate C++ templates.

Although C++ templates, Java generics, and .NET generics are often considered similar, generics only mimic the basic behavior of C++ templates.[7] Some of the advanced template features utilized by libraries such as Boost and STLSoft, and implementations of the STL, for template metaprogramming (explicit or partial specialization, default template arguments, template non-type arguments, template template arguments, ...) are unavailable with generics.

In C++ templates, compile-time cases were historically performed by pattern matching over the template arguments. For example, the template base class in the Factorial example below is implemented by matching 0 rather than with an inequality test, which was previously unavailable. However, the arrival in C++11 of standard library features such as std::conditional has provided another, more flexible way to handle conditional template instantiation.

// Induction
template<unsigned N> 
struct Factorial {
  static constexpr unsigned value = N * Factorial<N - 1>::value;
};

// Base case via template specialization:
template<> struct Factorial<0> {
  static constexpr unsigned value = 1;
};

With these definitions, one can compute, say 6! at compile time using the expression Factorial<6>::value.

Alternatively, constexpr in C++11 / if constexpr in C++17 can be used to calculate such values directly using a function at compile-time:

template<unsigned N>
unsigned factorial() {
    if constexpr(N<=1)
        return 1;
    else
        return N * factorial<N-1>();
}

Because of this, template meta-programming is now mostly used to do operations on types.

See also

[edit]

References

[edit]
  1. ^ Stroustrup, Bjarne (8 September 2004). "The C++ Programming Language". Stroustrup.com (personal homepage) (3rd, Special ed.).
  2. ^ "C++ Templates are Turing Complete" (PDF). ubietylab.net. Archived from the original (PDF) on 2025-08-08.
  3. ^ Lippman, Stan (11 August 2004). "Why C++ Supports both Class and Typename for Type Parameters". Microsoft Developers Network (MSDN).
  4. ^ "std::max". cppreference.com. Retrieved July 21, 2025.
  5. ^ "P1141R1 - Yet another approach for constrained declarations". Archived from the original on 2025-08-08. Retrieved 2025-08-08.
  6. ^ Vandevoorde, Daveed; Josuttis, Nicolai (2002). C++ Templates: The Complete Guide. Addison Wesley. ISBN 978-0-201-73484-3.
  7. ^ "Differences Between C++ Templates and C# Generics (C# Programming Guide)". 12 March 2024.
[edit]
自怨自艾什么意思 支气管扩张是什么原因引起 指甲变形是什么原因 cdfi是什么意思 什么的拳头
为什么老是恶心想吐 银镯子变黑是什么原因 半硬半软是什么症状 豆角不能和什么一起吃 星期一左眼皮跳是什么预兆
什么人不能吃玉米 1965属什么生肖 维生素吃多了有什么副作用 benny是什么意思 吃什么增强记忆力
婴儿头发竖起来是什么原因 健康的舌苔是什么样的 黑色碎花裙配什么上衣 dwi是什么检查 626什么星座
三点水加个真念什么hcv7jop6ns8r.cn 茵是什么意思hcv8jop6ns3r.cn 子宫内膜为什么会增厚hcv9jop7ns2r.cn 小孩子不吃饭是什么原因引起的hcv7jop6ns5r.cn 弱视什么意思hcv8jop9ns1r.cn
海豹油有什么作用hcv8jop2ns3r.cn 蛋白粉有什么营养hcv8jop3ns7r.cn 尿路感染是什么症状hcv9jop1ns9r.cn 什么是权力hcv9jop3ns6r.cn 老上火是什么原因造成的hcv8jop8ns0r.cn
乳头痛什么问题hcv9jop3ns0r.cn 刷脂是什么意思hcv8jop9ns8r.cn 虾滑是什么hcv7jop9ns1r.cn 金刚藤有什么功效dayuxmw.com 牛奶有什么营养hcv7jop9ns7r.cn
同比增长是什么意思hcv9jop0ns9r.cn 下肢动脉闭塞吃什么药hcv9jop7ns9r.cn 绿豆和什么相克中毒hcv9jop1ns8r.cn 头疼什么原因hcv7jop5ns6r.cn 脑动脉硬化吃什么药hcv8jop4ns5r.cn
百度