这是否是C++中的缺陷std :: get <T>(const std :: pair <const T,U>&)由于const T而无法编译?

rwo*_*ong 7 c++ c++14

如题.

当使用该std::get<T>(pair)对的第一个成员是const时,会发生此编译错误,该函数来自std::map或的迭代器std::unordered_map.

要测试编译错误,请注释掉"notstd"重载get.

我已经在Stack Overflow上研究了这个问题,下面列出了三个最相关的问题.

现有的答案让我相信它应该是一个缺陷报告,应该将相应的std::get重载添加到标准库中,并且应该扩展应用于临时常量引用的自动生命周期扩展以涵盖这种情况.

我还研究了它是否与布局的专业化有关(问题14272141,下面链接).但是,我的代码片段仅要求对两个成员之一的const引用; 即使布局专门化,对任一成员的const引用仍应存在.

根据现有的答案,我理解在两者之间铸造const std::pair<T, U>&并且const std::pair<const T, U>&不安全.

namespace notstd
{
    template <class T, class U>
    const T& get(const std::pair<const T, U>& tu)
    {
        return tu.first;
    }
}
int test(int value) 
{
    using namespace notstd;
    using namespace std;
    const std::pair<const int, bool> one(value, false);
    const auto two = get<int>(one);
    const auto three = get<const int>(one);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

相关性高的问题:

(谦卑通知:尽管我声称这看起来像是一个缺陷报告,但我脑子里可能有一些缺失的知识,所以请让我知道.从下面的rioki的答案中,我可以看到当前的设计允许区分这两个论点但是std::pair<const int, int>我的提议会失败.)

我对现状的描述:

  • 恼人的不一致,因为当两个成语(typed-get,并且始终使用基于范围的for vector<pair>和for unordered_map<pair>)一起使用时出现问题,并且对于这种不兼容性的解释对于包括初学者和有经验的程序员在内的任何人来说都不是完全适合的.
  • 正如rioki的回答所解释的那样,存在一个或多个令人满意的解决方法.
  • 也许不是缺陷报告(因为现有代码可能依赖于区分a const intint.)的能力,或者在不破坏现有代码的情况下无法改进.

Bar*_*rry 12

这是C++中std::get<T>(const std::pair<const T, U>& )由于const T?而无法编译的缺陷吗?

不,我非常希望这会失败:

std::pair<const int, bool> p(42, true);
std::get<int>(p); // expected failure
Run Code Online (Sandbox Code Playgroud)

std::get<T>意味着检索类型为的元素T.不是类型近似T,衰减T或任何其他类型的元素.std::get说到pair途经tuple,它被指定为:

要求:类型T恰好出现一次Types....否则,该计划是不正确的.

如果我们考虑pair作为一个特例tuple,int不会恰好发生一次{const int, bool},所以该程序应该是格式错误的.

换句话说:你要求int那对,但没有int.有一个const int,有一个bool.