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

标签 c++ c++11 templates

在下面的代码中,我想通过隐式转换 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/

相关文章:

c++ - 使用枚举成员模板化成员函数

Android NDK 无法编译示例应用程序

c++ - 使用非默认可构造类型填充 std::array(无可变参数模板)

javascript - 更新 polymer 元素模板

c++ - Eigen 库 : Take a copy of a templated function parameter

c++ - Bison 如何 "work": how is it used?

c++ - 如何在队列中存储位于 vector 中的对象的unique_ptr

c++ - 在没有 std::move 的情况下如何按值返回 unique_ptr?

c++ - initializer_list 和模板类型推导

c++ - 未找到使用表达式模板化的静态 constexpr 成员函数