我想限制构造函数仅将分配器作为参数,并且我提出了这个概念:
#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 情况下的分配器,但它没有检测到单个分配器。为什么这个概念不成立?
最佳答案
我的错,忘记了一个“*”...这是正确工作的更正版本(感谢@康桓伟以更加简洁)!
#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/