c++ 模板类型萃取技术_c模板类型标识技术

c++ 模板类型萃取技术

Templates are a useful feature with which we can define a generic function or a generic class that can be used with different types. To use the templates function, we need to specify the concrete types as the templates arguments on each call to the function. In practice, explicitly specifying all types for template functions can quickly become tedious, so instead of specifying them explicitly, we often let compiler to automatically determine the intended types. This is called templates argument deduction.

模板是一项有用的功能,通过它我们可以定义通用函数或可以用于不同类型的通用类。 要使用模板函数,我们需要在每次调用函数时将具体类型指定为模板参数。 在实践中,为模板函数显式指定所有类型很快就会变得乏味,因此,我们通常让编译器自动确定所需的类型,而不是显式地指定它们。 这称为模板参数推导。

The basic argument deduction process compares the type of the passed argument with the corresponding templates parameter T and try to conclude the correct substitution.

基本参数推导过程将传递的参数的类型与相应的模板参数T进行比较,并尝试得出正确的替换结果。

Let’s say there is a template function defined as below, that takes two arguments and return the sum of the two values.

假设有一个如下定义的模板函数,该函数接受两个参数并返回两个值的和。

template<class T>
T add(T a, T b) {
return a + b;
}

Instead of specifying the templates arguments explicitly, we can call the function with arguments with concrete types.

无需显式指定模板参数,我们可以使用具有具体类型的参数来调用函数。

auto sum = add<int>(1, 2);  // Explicit specification
auto sum = add(1, 2); // Implicit specification

In above example, the templates parameter T is substituted as int for both explicit and implicit specification cases.

在上面的示例中,对于显式和隐式规范情况,都将模板参数T替换为int

This all look simple so far but sooner the users of the templates function might stumble upon unexpected errors from seemingly innocent attempt like below,

到目前为止,这一切看起来都很简单,但是模板功能的用户可能会偶然发现如下所示的无辜尝试带来的意外错误,

auto sum = add(1, 2.5);  // Passing int(1) and double(2.5) as 
// templates arguments##### Error #####
templates argument deduction/substitution failed.

As you can see, passing 1 (int) and 2.5 (double) as the arguments of the templates function leads to a compiler error. Each argument is analysed independently in the deduction process, and the conclusions differ in the end (T deduced as int from the 1st argument, T deduced as double from the 2nd argument), hence the deduction process fails and compiler gives an error.

如您所见,将1(int)和2.5(double)用作模板函数的参数会导致编译器错误。 每个推论在推论过程中都是独立分析的,最终的结论是不同的( T从第一个论证推导为intT从第二个论证推导为double ),因此推论过程失败,编

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值