[英]Why does the implicit type conversion not work in template deduction?
在下面的代碼中,我想通過將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<typename Dtype>
void func(int a, Scalar<Dtype> b){
cout << "ok" <<endl;
}
template<typename Dtype>
void func(int a, Dtype b){
func(a, Scalar<Dtype>(std::move(b)));
}
模板參數推導是模式匹配,它只精確匹配類型或其基類型。 它沒有轉換。
稍后在重載決議和函數調用時完成轉換。
在這里,我們添加了另一個重載,該重載顯式轉發給您想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.