在下面的代码中,我想通过隐式转换 int
来调用模板函数。到 Scalar<int>
对象。
#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;
}
为什么模板参数推导/替换失败?并且注释代码也是错误的。
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);
最佳答案
因为template argument deduction不是那么聪明:它(按设计)不考虑用户定义的转换。和int
-> Scalar<int>
是用户定义的转换。
如果你想使用TAD,你需要在调用者站点转换你的参数:
func(a, Scalar<int>{2});
或为Scalar
定义一个扣除指南1并调用f
:
func(a, Scalar{2}); // C++17 only
或者,您可以显式实例化 f
:
func<int>(a, 2);
1) 默认扣指南就足够了:demo .
关于c++ - 为什么隐式类型转换在模板推导中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53227713/