c++ - 使用 C++20 概念将函数参数约束为分配器

标签 c++ c++-concepts allocator

我想限制构造函数仅将分配器作为参数,并且我提出了这个概念:

Demo

#include <iostream>
#include <string>
#include <memory>
#include <memory_resource>
#include <vector>
#include <concepts>
#include <utility> /* declval */

template <typename Allocator> 
concept is_allocator = requires(Allocator a) {
    typename Allocator::value_type;
    { a.allocate(std::declval<std::size_t>()) } -> std::same_as<typename Allocator::value_type*>;
    { a.deallocate(std::declval<typename Allocator::value_type>(), std::declval<std::size_t>()) } -> std::same_as<void>;
};

template <typename T>
struct MyAllocator {
    using value_type = T;
    auto allocate(std::size_t size) -> T*;
    auto deallocate(T*, std::size_t size) -> void;
};

int main() {
    using A1 = std::allocator<int>;
    using A2 = std::pmr::polymorphic_allocator<std::byte>;
    using B = MyAllocator<int>;
    using C = std::string;


    if constexpr(is_allocator<A1>) {
        std::cout << "A1 is an allocator" << std::endl;
    }
    if constexpr(is_allocator<A2>) {
        std::cout << "A2 is an allocator" << std::endl;
    }
    if constexpr(is_allocator<B>) {
        std::cout << "B is an allocator" << std::endl;
    }
    if constexpr(is_allocator<C>) {
        std::cout << "C is an allocator" << std::endl;
    }
}

我期望它能够检测 A1、A2、B 和 C 情况下的分配器,但它没有检测到单个分配器。为什么这个概念不成立?

最佳答案

我的错,忘记了一个“*”...这是正确工作的更正版本(感谢@康桓伟以更加简洁)!

Demo

#include <iostream>
#include <string>
#include <memory>
#include <memory_resource>
#include <vector>
#include <concepts>

template <typename Allocator> 
concept is_allocator = requires(Allocator a, typename Allocator::value_type* p) {
    { a.allocate(0) } -> std::same_as<decltype(p)>;
    { a.deallocate(p, 0) } -> std::same_as<void>;
};

template <typename T>
struct MyAllocator {
    using value_type = T;
    auto allocate(std::size_t size) -> T*;
    auto deallocate(T*, std::size_t size) -> void;
};

int main() {
    using A1 = std::allocator<int>;
    using A2 = std::pmr::polymorphic_allocator<std::byte>;
    using B = MyAllocator<int>;
    using C = std::string;


    if constexpr(is_allocator<A1>) {
        std::cout << "A1 is an allocator" << std::endl;
    }
    if constexpr(is_allocator<A2>) {
        std::cout << "A2 is an allocator" << std::endl;
    }
    if constexpr(is_allocator<B>) {
        std::cout << "B is an allocator" << std::endl;
    }
    if constexpr(is_allocator<C>) {
        std::cout << "C is an allocator" << std::endl;
    }
}

关于c++ - 使用 C++20 概念将函数参数约束为分配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76582347/

相关文章:

android - Qt 中是否有#ifdef 来确定我们是否正在为 Android 构建

c++ - 为什么这段代码会发出 SIGSEGV 信号?

algorithm - 选择排序算法的标准

c++ - 只要 std::allocator_traits<T> 是专门的,我可以使用任何类 T 作为分配器类型吗?

C++自定义分配器: const_pointer 'has not been declared'

C++ 如何在容器类复制构造函数中复制分配器对象

c++ - Visual Studio 2008 C++ 语言支持?

C++ GTKmm - 将文本插入到具有多个缓冲区和更改文本的 TextView

C++ 概念精简版和类型别名声明

c++ - 否定一个概念 (C++20)