Home  >  Article  >  Backend Development  >  Why Does Implicit Type Conversion Fail in Template Deduction?

Why Does Implicit Type Conversion Fail in Template Deduction?

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 19:31:30231browse

 Why Does Implicit Type Conversion Fail in Template Deduction?

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 object. However, surprisingly, the code fails to compile due to template argument deduction/substitution failing for the first call to func(a, 2).

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 is a user-defined conversion, which is not automatically applied during template argument deduction.

To resolve this issue, there are several options:

  • Explicit Conversion at Caller Site: Force the conversion by manually providing a Scalar object with the desired value at the call site:

    <code class="cpp">func(a, Scalar<int>{2}); </code>
  • Deduction Guide: Define a deduction guide for Scalar and call func:

    <code class="cpp">func(a, Scalar{2}); // C++17 only</code>

    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:

    <code class="cpp">func<int>(a, 2); </code>

    This works only if Scalar::Scalar(T) is not explicit.

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!

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