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
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. [ 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 !
In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.
An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.
Function templates are similar to class templates but define a family of functions. With function templates, you can specify a set of functions that are based on the same code but act on different types or classes. The following function template swaps two items: C++ Copy.
Class Template Argument Deduction (CTAD) is a C++17 Core Language feature that reduces code verbosity. C++17's Standard Library also supports CTAD, so after upgrading your toolset, you can take advantage of this new feature when using STL types like std::pair and std::vector.
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. There is a standard conversion from int
to double
and a user defined conversion from double
to Complex
.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With