has_iterator 如何在给定代码中工作?

How has_iterator is working in given code?

请考虑以下程序:

    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)

您的起点是正确的。在模板参数替换发生后,重载决议将在

之间进行选择
static char test<std::vector<int>>(std::vector<int>::iterator* x);

static long test<std::vector<int>>(std::vector<int>* x);

认为这会模棱两可是有道理的。 0 同样可以转换为任一指针类型。

这仍然有效的原因仅仅是因为重载决议有一个决胜局,其中更专业的函数模板比​​更通用的函数模板更受欢迎。第一个功能模板比较专业