为什么隐式类型转换在模板推导中不起作用?

编程入门 行业动态 更新时间:2024-10-25 00:26:25
本文介绍了为什么隐式类型转换在模板推导中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在下面的代码中,我想通过将 int 隐式转换为 Scalar 对象来调用模板函数.

In the following code, I want to call a template function by implicitly converting an int to a Scalar<int> object.

#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); 
  //int b = 2;
  //func(a, b);
  return 0;
}

为什么模板参数推导/替换失败?注释代码也是错误的.

Why does the template argument deduction/substitution fail? And the commented-codes are also wrong.

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

推荐答案

因为 模板参数推导 不是那么聪明:它(按设计)不考虑用户定义的转换.而 int -> Scalar 是用户定义的转换.

Because template argument deduction is not that smart: it does not (by design) consider user-defined conversions. And int -> Scalar<int> is a user-defined conversion.

如果你想使用 TAD,你需要在调用者站点转换你的参数:

If you want to use TAD, you need to convert your argument at the caller site:

func(a, Scalar<int>{2}); 

或为Scalar定义一个推导指南1并调用f:

or define a deduction guide1 for Scalar and call f:

func(a, Scalar{2}); // C++17 only

或者,您可以显式实例化 f:

Alternatively, you can explicitly instantiate f:

func<int>(a, 2); 

<小时>

1)默认推导就足够了:demo.

这篇关于为什么隐式类型转换在模板推导中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 06:22:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405170.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中不   模板   类型   隐式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!