【问题标题】:C++ - Ambiguous Overloaded Template Resolution/DeductionC++ - 模棱两可的重载模板解析/演绎
【发布时间】:2019-08-04 17:19:45
【问题描述】:

运行以下代码 sn-p,我没有收到任何错误,并且得到了预期的结果。但是,由于第二个模板实例化不明确(both type specifiers are references),我担心这可能不是定义的行为。
这种行为(编译器实例化最具体的重载模板)是否得到保证?强>

#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;
}

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

【问题讨论】:

  • 推论规则不容易遵循和理解,但你的代码表现得像它应该的那样。没什么好担心的。
  • 来自cppreference partial ordering selects ... as more specializedInformally "A is more specialized than B" means "A accepts fewer types than B".
  • 谢谢大家。 @super 这正是我想要的!

标签: c++ c++11 templates language-lawyer type-deduction


【解决方案1】:

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

【讨论】:

  • 谢谢!我刚刚添加了语言律师标签。不知道这种行为是不是按照扣分规则来保证?
  • @pooya13,是的。
猜你喜欢
  • 1970-01-01
  • 2015-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
  • 2010-12-10
  • 2015-10-12
相关资源
最近更新 更多