为了使容器既能与C++11兼容,又能与pmr分配器兼容,需要在容器的实现中引入if constexpr语句来判断使用哪种类型的分配器。下面是使用std::vector的示例代码:
#include
#include
template
class MyContainer
{
public:
template
void reserve(size_t n, Allocator allocator)
{
if constexpr (std::is_same_v>)
{
data_.reserve(n, allocator);
}
else
{
data_.reserve(n);
}
}
private:
std::vector data_;
};
在reserve()函数中,使用if constexpr语句来判断Allocator是否是std::pmr::polymorphic_allocator