Home  >  Article  >  Backend Development  >  Why Does Template Argument Deduction Fail with User-Defined Conversions?

Why Does Template Argument Deduction Fail with User-Defined Conversions?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 16:20:29386browse

 Why Does Template Argument Deduction Fail with User-Defined Conversions?

Template Argument Deduction and User-Defined Conversions

In C template programming, a common task is to pass a value of one type into a template function that expects an argument of a different type. To facilitate this, the compiler provides template argument deduction (TAD), which can automatically infer the template arguments based on the types of the actual arguments.

Limits of Template Argument Deduction

However, there are limitations to TAD. One limitation is that it does not consider user-defined conversions. This means that if you have a user-defined conversion from one type to another, TAD will not apply that conversion to infer the template arguments.

Case Study

Consider the following code snippet:

<code class="cpp">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); // Error
}

In this code, we have a template function that takes two arguments: an integer a and a Scalar object of some type Dtype. In the main function, we try to call func by passing an integer a and an integer 2. However, this fails with a compilation error:

test.cpp: In function ‘int main()’:
test.cpp:32:12: error: no matching function for call to ‘func(int&, int)’
   func(a, 2);
            ^
test.cpp:32:12: note: candidate is:
test.cpp:25:6: note: template<class Dtype> void func(int, Scalar<Dtype>)
 void func(int a, Scalar<Dtype> b){
      ^
test.cpp:25:6: note:   template argument deduction/substitution failed:
test.cpp:32:12: note:   mismatched types ‘Scalar<Dtype>’ and ‘int’
   func(a, 2);</code>

Why TAD Fails

The reason for the failure is that TAD cannot apply the user-defined conversion from int to Scalar. To make this work, we need to either explicitly convert the argument at the caller site or define a deduction guide for Scalar.

The above is the detailed content of Why Does Template Argument Deduction Fail with User-Defined Conversions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn