Home >Backend Development >C++ >Why Does Template Argument Deduction Fail with Implicit Type Conversions in C ?
Template Argument Deduction and Implicit Type Conversion
In C , template argument deduction is a powerful feature that automatically determines the types of template parameters based on the caller's arguments. However, certain types of conversions are not considered during deduction, including user-defined conversions.
Problem with Implicit Conversion
Consider the following code snippet:
<code class="cpp">template<typename Dtype> class Scalar{ Scalar(Dtype v) : value_(v){} private: Dtype value_; };</code>
The Scalar class represents a simple value type. Now, consider the following template function:
<code class="cpp">template<typename Dtype> void func(int a, Scalar<Dtype> b){ cout << "ok" <<endl; }</code>
This function takes an int and a Scalar
In the following main function, we attempt to call func with an int and an int value:
<code class="cpp">int main(){ int a = 1; func(a, 2); // ERROR: template argument deduction fails return 0; }</code>
But this results in a compilation error, stating that the template argument deduction failed. This is because the compiler cannot automatically convert the int value 2 to a Scalar
Possible Solutions
To fix this issue, you have several options:
Explicit Conversion at Caller Site:
<code class="cpp">func(a, Scalar<int>(2));</code>
This manually converts the int value to a Scalar
Deduction Guide: (C 17 only)
Add a deduction guide for Scalar:
<code class="cpp">template<typename T> Scalar(T v) -> Scalar<T>;</code>
This tells the compiler to prefer this deduction guide when deducing the type of Scalar from the caller's argument, allowing you to call func as:
<code class="cpp">func(a, 2);</code>
Explicit Instantiation:
You can explicitly instantiate func for a specific type:
<code class="cpp">func<int>(a, 2);</code>
This forces the compiler to instantiate the function with Dtype = int, circumventing the need for template argument deduction.
The above is the detailed content of Why Does Template Argument Deduction Fail with Implicit Type Conversions in C ?. For more information, please follow other related articles on the PHP Chinese website!