首页 > 解决方案 > C++ - 模棱两可的重载模板解析/演绎

问题描述

运行以下代码片段,我没有收到任何错误,并且得到了预期的结果。但是,由于第二个模板实例化是模棱两可的(两个类型说明符都是引用),我担心这可能不是定义的行为。
这种行为(编译器实例化最具体的重载模板)是否得到保证?

#include <algorithm>
#include <iostream>
#include <vector>

template<typename T>
void Print(const T& x)
{
    std::cout << x << std::endl;
}

template<typename T>
void Print(const std::vector<T>& x)
{
    for(auto it = x.begin(); it != x.end(); ++it)
    {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
}

int main(int argc, char const *argv[])
{
    std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    Print(5); // 5
    Print(v); // 0 1 2 3 4 5 6 7 8 9

    return 0;
}

我不知道在哪里看所以一个很好的参考也非常感谢。

标签: c++c++11templateslanguage-lawyertype-deduction

解决方案


const std::vector<T>& x是比 更专业的类型const T& x。更专业的类型被认为更适合重载解析。因此,您的代码的行为应该如此。


推荐阅读