这是否是C中的缺陷,因为const T,std :: get(const std :: pair&)无法编译?

前端之家收集整理的这篇文章主要介绍了这是否是C中的缺陷,因为const T,std :: get(const std :: pair&)无法编译?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如题.

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

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

我已经在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;
}

相关性高的问题:

> Bind const std::pair<T,U>& to value of std::pair<const T,U>
> Is casting std::pair<T1,T2> const& to std::pair<T1 const,T2> const& safe?
> std::is_assignable and std::pair<const T,U>

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

我对目前情况的描述:

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

解决方法

Is this a defect in C++ that std::get<T>(const std::pair<const T,U>& ) fail to compile due to const T?

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

std::pair<const int,bool> p(42,true);
std::get<int>(p); // expected failure

的std ::得到< T>表示检索类型为T的元素.不是类型近似为T,或衰减为T的元素,或任何其他类型的元素. std :: get通过元组来对,它是specified as

Requires: The type T occurs exactly once in Types.... Otherwise,the program is ill-formed.

如果我们将pair视为元组的特例,则int在{const int,bool}中不会出现一次,因此程序应该是格式错误的.

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

原文链接:https://www.f2er.com/c/119616.html

猜你在找的C&C++相关文章