问题描述
限时送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:关键词]
发布评论