Joh*_*don 7 c++ templates implicit
我有以下代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
当我用gcc 4.3.3编译代码时,我得到一个message(aaa.cc:17: error: no matching function for call to ‘tf(pointer<float>&)’),指示编译器调用'operator pointer<const T>'了非模板化函数f(),但没有用于模板化函数tf().为什么并且有没有解决方法没有使用const和非const版本重载tf()?
在此先感谢您的帮助.
原因是您在模板推导期间没有获得隐式类型转换,它永远不会到达那一点.
考虑:
template <typename T>
struct foo {};
template <typename U>
void bar(foo<U>)
{}
foo<int> f;
bar(f);
Run Code Online (Sandbox Code Playgroud)
对于对bar的调用,编译器可以推断出它U是一个int,并实例化该函数.但是,请考虑:
template <typename U>
void bar(foo<const U>)
{} // note ^^^^
foo<int> f;
bar(f);
Run Code Online (Sandbox Code Playgroud)
没有U编译器可以推断出foo匹配类型的参数类型.因此,模板实例化失败.转换没有机会发生.