gpt4 book ai didi

c++ - 如何为 unordered_map 定义一个检测其删除功能的概念

转载 作者:行者123 更新时间:2023-12-02 02:26:01 24 4
gpt4 key购买 nike

我正在为无序关联容器编写一个 C++ 概念,即 std::unordered_map。我很难检测到删除功能(也可以插入,但暂时忽略它)。

这是我的概念尝试,遗憾的是,当我尝试调用需要它的模板化函数时,它失败了。

template <class _ContainerType_>
concept InsertErasable = requires(_ContainerType_ a)
{
{ a.erase( _ContainerType_::const_iterator) } -> typename _ContainerType_::iterator;
};

我这样使用它:

template<InsertErasable _ContainerType_>
inline void Test123( const _ContainerType_& container )
{
return;
}

std::unordered_map<std::string, int> map;
::Test123(map);

error C7602: 'Test123': the associated constraints are not satisfied

使用最新的 Visual Studio 2019。

它应该检测此处显示的第一个删除签名: https://en.cppreference.com/w/cpp/container/unordered_map/erase

知道我做错了什么吗?

最佳答案

老实说,我从未在实践中使用过概念,但我设法找出这里出了什么问题。 require 子句中的代码必须是表达式,而不是半表达式、半函数定义。换句话说,如果将它放在常规函数中(require 子句中的 https://en.cppreference.com/w/cpp/language/constraints 部分),它必须是一个可以编译的表达式。要解决您的问题,您必须将概念子句内的代码调整为有效的 C++ 表达式。这可以通过两种方式之一完成。要么:

template <class _ContainerType_>
concept InsertErasable = requires(_ContainerType_ a)
{
{a.erase(a.cbegin())} -> typename _ContainerType_::iterator;
};

template <class _ContainerType_>
concept InsertErasable = requires(_ContainerType_ a,_ContainerType_::const_iterator b)
{
{a.erase(b)} -> typename _ContainerType_::iterator;
};

Example on compiler explorer

关于c++ - 如何为 unordered_map 定义一个检测其删除功能的概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60494831/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com