为什么模板化函数不隐式调用运算符转换? (C++)
我有以下代码:
template <class T>
struct pointer
{
operator pointer<const T>() const;
};
void f(pointer<const float>);
template <typename U>
void tf(pointer<const U>);
void g()
{
pointer<float> ptr;
f(ptr);
tf(ptr);
}
当我使用 gcc 4.3.3 编译代码时,我收到一条消息 (aaa.cc:17: error: nomatching function for call to 'tf(pointer
'操作符指针
,但对于模板化函数 tf() 则没有调用。为什么除了使用 const 和非常量版本重载 tf() 之外,是否有任何解决方法?
预先感谢您的任何帮助。
I have the following code:
template <class T>
struct pointer
{
operator pointer<const T>() const;
};
void f(pointer<const float>);
template <typename U>
void tf(pointer<const U>);
void g()
{
pointer<float> ptr;
f(ptr);
tf(ptr);
}
When I compile the code with gcc 4.3.3 I get a message (aaa.cc:17: error: no matching function for call to ‘tf(pointer<float>&)’
) indicating that the compiler called 'operator pointer<const T>'
for the non-templated function f(), but didn't for the templated function tf(). Why and is there any workaround short of overloading tf() with a const and non-const version?
Thanks in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
原因是在模板推导过程中您没有获得隐式类型转换,它永远不会达到这一点。
考虑一下:
对于对 bar 的调用,编译器可以推断出
U
是一个int
,并实例化该函数。但是,请考虑:编译器无法推断出
U
使得foo
的类型与参数的类型相匹配。因此,模板实例化失败。没有机会发生转换。The reason is that you don't get implicit type conversions during template deduction, it never gets to that point.
Consider:
For that call to bar, the compiler can deduce that
U
is anint
, and instantiate the function. However, consider:There is no
U
the compiler can deduce such that the type offoo
matches the type of the parameter. Ergo, template instantiation fails. There is no chance for the conversion to happen.^ 除非您在函数调用时显式指定参数类型,否则编译器不会将函数调用与此函数匹配,因为您不使用类型名称
U
作为函数参数。我怀疑你想做类似的事情:^ The compiler won't match a function call to this function unless you explicitly specify a parameter type at the function call, since you don't use the typename
U
as a function argument. I suspect you want to do something like: