为什么模板函数不能自动调用运算符转换?(C++)

7

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);
}

当我使用gcc 4.3.3编译代码时,出现了错误信息(aaa.cc:17: error: no matching function for call to ‘tf(pointer&)’),这表明编译器对于非模板函数f()调用了operator pointer,但是却没有对于模板函数tf()进行调用。为什么会这样?是否有任何解决方法,而不需要重载tf()来创建一个const和non-const版本?
非常感谢您的帮助!

也许是stackoverflow的软件移除了你的模板尖括号? - jonner
2个回答

6
原因在于模板推导过程中不会发生隐式类型转换,所以它永远不会到达那一步。请考虑:
template <typename T>
struct foo {};

template <typename U>
void bar(foo<U>)
{}

foo<int> f;
bar(f);

在调用bar函数时,编译器可以推断出U是一个int类型,并实例化该函数。但是,请考虑以下情况:

template <typename U>
void bar(foo<const U>)
{}  // note  ^^^^

foo<int> f;
bar(f);

编译器无法推断出任何U类型,使得foo的类型与参数的类型匹配。因此,模板实例化失败。没有机会进行转换。


1
template <typename U>
void tf(pointer<const float>);

编译器不会将函数调用与此函数匹配,除非您在函数调用时显式指定参数类型,因为您没有将typename U用作函数参数。我怀疑您想做的是:

template <typename U>
void tf(pointer<U>);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接