简体   繁体   English

显式模板函数参数规范和C ++ 11中函数参数的隐式转换

[英]Explicit template function argument specification and Implicit conversion of function arguments in C++11

Title of the topic is long and cryptic, but question is rather simple. 这个主题的标题很长而且含糊不清,但问题很简单。

I am reading 14.8.1 Explicit template argument specification in the latest C++11 Specs draft(N3242=11-0012), page 375 我正在阅读14.8.1 Explicit template argument specification最新C ++ 11规范草案中的14.8.1 Explicit template argument specification (N3242 = 11-0012),第375页

6 Implicit conversions (Clause 4) will be performed on a function argument to convert it to the type of the corresponding function parameter if the parameter type contains no template-parameters that participate in template argument deduction. 6如果参数类型不包含参与模板参数推导的模板参数,则将对函数参数执行隐式转换(第4节),以将其转换为相应函数参数的类型。 [ Note: Template parameters do not participate in template argument deduction if they are explicitly specified. [注意:如果明确指定模板参数,则模板参数不参与模板参数推断。 For example, 例如,

template<class T> void f(T);
class Complex {
  Complex(double);
};
void g() {
  f<Complex>(1); // OK, means f<Complex>(Complex(1))
}

—end note ] - 尾注]

Could someone explain to me, what it trying to say and where is the conversion taking place in the example. 有人可以向我解释一下,它试图说什么,以及示例中发生的转换在哪里。
Thanks ! 谢谢 !

The conversion is taking place right here: 转换正在这里进行:

f<Complex>(1);

You are calling a function f that expects a Complex , but you are passing it an int instead. 你正在调用一个期望一个Complex的函数f ,但你传递的是一个int There is a standard conversion from int to double and a user defined conversion from double to Complex . 有一个从intdouble标准转换 ,以及用户定义的doubleComplex 转换

What the standard is trying to say is that when you explicitly provide template arguments to a template function, those behave as if the function was declared with those types. 该标准试图说明的是,当您明确地向模板函数提供模板参数时,这些参数就像使用这些类型声明函数一样。 That is, when you call f<Complex> it behaves as if declared: 也就是说,当你调用f<Complex>它的行为就像声明:

void f( Complex );

Otherwise, had the template parameter not being explicitly specified, T would have been deduced to be int and no implicit conversion would have taken place. 否则,如果未明确指定模板参数,则T将被推断为int并且不会发生隐式转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM