Implicit Type Conversion in Template Deduction
In C , the implicit type conversion mechanism plays a crucial role in template argument deduction. However, in certain scenarios, it can lead to unexpected behavior, as illustrated by the code snippet below:
<code class="cpp">#include<iostream> using namespace std; template<typename Dtype> class Scalar{ public: Scalar(Dtype v) : value_(v){} private: Dtype value_; }; template<typename Dtype> void func(int a, Scalar<Dtype> b){ cout << "ok" << endl; } int main(){ int a = 1; func(a, 2); // Incorrect conversion //int b = 2; //func(a, b); // Also incorrect return 0; }
In the provided code, the goal is to invoke the template function func by implicitly converting an int to a Scalar The reason behind this failure is that template argument deduction does not consider user-defined conversions. In this scenario, the conversion from int to Scalar To resolve this issue, there are several options: Explicit Conversion at Caller Site: Force the conversion by manually providing a Scalar Deduction Guide: Define a deduction guide for Scalar and call func: This approach relies on the default deduction guide, which is sufficient in this case. Explicit Instantiation: Explicitly instantiate the func template for the desired type: This works only if Scalar In conclusion, template argument deduction does not automatically apply user-defined conversions. To use user-defined conversions in template argument deduction, it is necessary to either explicitly convert the argument at the caller site, use a deduction guide if applicable, or explicitly instantiate the template for the desired type. The above is the detailed content of Why Does Implicit Type Conversion Fail in Template Deduction?. For more information, please follow other related articles on the PHP Chinese website!
<code class="cpp">func(a, Scalar<int>{2}); </code>
<code class="cpp">func(a, Scalar{2}); // C++17 only</code>
<code class="cpp">func<int>(a, 2); </code>