【发布时间】:2015-10-02 04:16:25
【问题描述】:
#include <iostream>
template<typename T>
struct identity
{
typedef T type;
};
template<typename T> void bar(T) { std::cout << "a" << std::endl; }
template<typename T> void bar(typename identity<T>::type) { std::cout << "b" << std::endl; }
int main ()
{
bar(5); // prints "a" because of template deduction rules
bar<int>(5); // prints "b" because of ...?
return EXIT_SUCCESS;
}
我预计bar<int>(5) 至少会产生歧义。这里涉及到什么关于模板函数重载解析的疯狂规则?
【问题讨论】:
-
我会说
typename identity<T>::type比T更专业。 -
@Jarod42
typename identity<int>::type只是语法上更冗长的表达方式int;它并不表示更专业的int。如果我们在两个函数中用int替换模板参数T,我们会得到一个只使用int,另一个使用typename identity<int>::type。 这应该是模棱两可的。我的意思是,假设您有一个简单的 A 类,其中包含typedef int B。与在同一参数位置使用int的函数相比,您不会优先考虑使用A::B的函数。
标签: c++ templates language-lawyer overload-resolution