请考虑以下计划:
template <typename T>
struct has_iterator
{
template <typename U>
static char test(typename U::iterator* x);
template <typename U>
static long test(U* x);
static constexpr const bool value = sizeof(test<T>(0)) == 1;
};
int main() {
std::cout << std::boolalpha << has_iterator<std::vector<int>>::value << std::endl;
return 0;
}
上述程序的输出为真。我的问题是当T为std::vector<int>
时为什么static char test(typename U::iterator* x)
优先于static long test(U* x)
。
答案 0 :(得分:3)
你是以正确的方式开始的。在发生模板参数替换之后,可以在
之间选择重载决策static char test<std::vector<int>>(std::vector<int>::iterator* x);
和
static long test<std::vector<int>>(std::vector<int>* x);
认为这是模棱两可的是有道理的。 0
同样可以转换为指针类型。
这仍然有效的原因很简单,因为重载决策有一个决胜局,其中一个更专业的功能模板优于更通用的功能模板。第一个功能模板更专业。