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

标签 c++ c++-concepts

我正在为无序关联容器编写一个 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/

相关文章:

C++ 约束 enable_if 与 requires

c++ - 如何在没有管理权限的情况下为我的应用程序实现自动更新

C++11 通过原始指针或引用获取 unique_ptr 的所有权?

c++ - 使用 Catch2 编译多个测试源的正确方法是什么?

c++ - 从二进制编码中提取小时、分钟和秒

c++ - 在概念定义中,是否允许在 requires 表达式之外出现替换失败?

c++ - 学习 C++ 和 SDL- 以下是否会产生内存泄漏?

c++ - Windows 上的 C++17 是否与 ubuntu 上的 C++17 一致?

c++ - 概念 : checking signatures of methods with arguments

使用概念具有特定值类型的任何容器的 C++ 迭代器