如何向类传递分配器类型,无需指定其成员的类型?
问题:简化分配器类型的传递写法
我希望向一个类传递分配器类型,不需要客户端指定该类成员的类型。初始实现如下:
#include <string> #include <memory> #include <vector> template<typename STRALLOC, typename INTALLOC> struct Thing { std::vector<std::string, STRALLOC> string_content; std::vector<int, INTALLOC> int_content; }; int main() { Thing<std::allocator<std::string>, std::allocator<int>> heapStuff; Thing<std::pmr::polymorphic_allocator<std::string>, std::pmr::polymorphic_allocator<int>> polyStuff; return 0; }
这种方式需要分别指定string和int对应的分配器类型,使用起来很繁琐。我期望采用如下更简洁的写法:
template<typename ALLOC> struct Thing { std::vector<std::string, ALLOC<std::string>> string_content; std::vector<int, ALLOC<int>> int_content; }; int main() { Thing<std::allocator> heapStuff; Thing<std::pmr::polymorphic_allocator> polyStuff; return 0; }
但这种写法无法运行,因为std::allocator缺少模板参数时并非一个类型。请问有没有办法实现这种简化?
解决方案
实际上实现方法很简单,通过模板模板参数即可解决:
#include <string> #include <memory> #include <vector> template<template<class> typename ALLOCATOR> struct Thing { std::vector<std::string, ALLOCATOR<std::string>> string_content; std::vector<int, ALLOCATOR<int>> int_content; }; int main() { Thing<std::allocator> heapStuff; Thing<std::pmr::polymorphic_allocator> polyStuff; return 0; }
内容的提问来源于stack exchange,提问作者Den-Jason
相关产品推荐
相关产品推荐

