dan*_*vey 6 c++ templates overload-resolution
在下面,为什么调用bar不明确的实例化,而非模板重载函数foo是不明确的.nullptr取而代之的是相同的NULL
#include <iostream>
template<typename T>
void bar (T*)
{
std::cout << "bar(T*)" << std::endl;
}
template<typename T>
void bar (typename T::value_type *)
{
std::cout << "bar(T::value_type*)" << std::endl;
}
struct A
{
using value_type = int;
};
void foo (A::value_type*)
{
std::cout << "foo(A::value_type *)" << std::endl;
}
void foo (A*)
{
std::cout << "foo(A *)" << std::endl;
}
int main ()
{
bar<A> (NULL);
foo (NULL); // ambigous
}
Run Code Online (Sandbox Code Playgroud)
编辑:要清楚.我希望foo过载是模棱两可的.我不明白为什么bar我实例化时产生的重载bar<A>不是同样模棱两可.
在解决作为函数模板实例化的函数重载之间的歧义时,还有一条附加规则:重载函数模板的部分排序( [temp.func.order] )。
\n\n这通常用于解决歧义,有利于更专门的重载函数模板:
\n\ntemplate<typename T> void f(T) { ... }\ntemplate<typename T> void f(T*) { ... } // specialization for pointers\nvoid g() { int i; f(&i); } // calls f<int>(int*), not f<int*>(int*)\nRun Code Online (Sandbox Code Playgroud)\n\n然而,由于规则的设置方式([over.match.best] /1),即使模板参数(此处T := A)不是通过模板参数推导从参数中推导出来的,函数模板部分排序也适用,即使它是由明确的专业化提供:
\n\n\n[...]
\n
\n \xe2\x80\x94F1和F2是函数模板特化,并且 的函数模板F1比F2根据 14.5.6.2 中描述的部分排序规则的模板更特化。
这里被认为比(在[temp.func.order]bar(A::value_type *)下)更专业,因此首选前者并且没有歧义。bar(A *)
| 归档时间: |
|
| 查看次数: |
487 次 |
| 最近记录: |