为什么隐式类型转换在模板扣除中不起作用?
在以下代码中,我想通过将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);
In the following code, I want to call a template function by implicitly converting an int
to a Scalar<int>
object.
#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;
}
Why does the template argument deduction/substitution fail? And the commented-codes are also wrong.
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为 template参数ducation 不是那么聪明:它不是(按设计),考虑用户定义的转换。和
int
- &gt;标量&lt; int&gt;
是用户定义的转换。如果要使用TAD,则需要在呼叫者站点上转换参数:
或定义扣除指南 1
scalar
并调用f
:另外,您可以明确实例化
f
(仅当scalar&lt; t&gt; :: starcar(t)
is notequarlicit
):1) 默认值扣除指南就足够了: demo 。
Because template argument deduction is not that smart: it does not (by design) consider user-defined conversions. And
int
->Scalar<int>
is a user-defined conversion.If you want to use TAD, you need to convert your argument at the caller site:
or define a deduction guide1 for
Scalar
and callf
:Alternatively, you can explicitly instantiate
f
(only works ifScalar<T>::Scalar(T)
is notexplicit
):1) The default deduction guide is sufficient: demo.
模板参数扣除是模式匹配,它仅与完全匹配的类型或基本类型。它没有转换。
转换以后进行,以分辨率分辨率&amp;功能致电时间。
在这里,我们将另一个明确将其转发到您想要的过载。
template argument deduction is pattern matching, and it only matches the types or their base types exactly. It does no conversion.
Conversion is done later, at overload resolution & function call time.
Here, we add another overload that explicitly forwards to the one you want.