簡體   English   中英

為什么隱式類型轉換在模板推導中不起作用?

[英]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);

因為模板參數推導不是那么聰明:它(設計)不考慮用戶定義的轉換。 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

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM