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

Yul*_* Ao 12 c++ templates c++11

在下面的代码中,我想通过隐式转换intScalar<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;
}
Run Code Online (Sandbox Code Playgroud)

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

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);
Run Code Online (Sandbox Code Playgroud)

YSC*_*YSC 14

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

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

func(a, Scalar<int>{2}); 
Run Code Online (Sandbox Code Playgroud)

或限定一个导向扣1Scalar并调用f:

func(a, Scalar{2}); // C++17 only
Run Code Online (Sandbox Code Playgroud)

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

func<int>(a, 2); 
Run Code Online (Sandbox Code Playgroud)

1)默认扣减指南就足够了:演示.