c++ - 由用于构造不同类型容器的分配器参数化的函数模板

标签 c++ allocator

我想要一个函数 foo 沿着这些线

template <class T, class Alloc>
void foo(T param, Alloc a) {
    vector<int, Alloc<int> > vect_of_ints;
    list<float, Alloc<float> > list_of_floats;
    do_something()
}

std::allocator a
foo(42, a);

这失败了,我认为是因为 std::allocator 不是一个定义明确的类型,直到它被特殊化为特定类型。有没有可能做我想做的事,但以其他方式。

最佳答案

您不能拥有分配器 (a) 的一个实例并期望它适用于 2 种不同的类型。但是,您可以使用分配器泛型类型(模板模板参数),并以两种不同的方式在您的 foo() 中专门化它。 无论如何,您都没有在 foo() 上使用“a”。

template <template<class> class Alloc, class T>
void foo(T t1, T t2) {
    vector<int, Alloc<int> > vect_of_ints;
    list<float, Alloc<float> > list_of_floats;
    do_something()
}

// UPDATE: You can use a function wrapper, and then the compiler will be
// able to figure out the other types.
template<class T>
void foo_std_allocator(T t1, T t2)
{
    foo<std::allocator, T>(t1, t2);
}


int main()
{
    //std::allocator a;
    //foo<std::allocator>();
    foo<std::allocator, int>(1, 2);

    // in the call below, the compiler easily identifies T as int.
    // the wrapper takes care of indicating the allocator
    foo_std_allocator(1, 2);

    return 0;
}

关于c++ - 由用于构造不同类型容器的分配器参数化的函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13171717/

相关文章:

c++ - 如何知道元素是否是 vector 中的最后一个元素使用 for(int i :myVector) code style?

c++ - 我如何知道 ARM 库是否正在使用 hardfp?

c++ - 在 C++ 中通过 SSH 隧道连接到 MySQL

c++ - c++ 中的 time(NULL) 只计算秒,不计算毫秒

c++ - 默认 move 构造函数中的赋值顺序是什么?

c++ - libstdc++ 对 std::unordered_map 的支持是否不完整?

C++ 分配器,特别是将构造函数参数传递给使用 boost::interprocess::cached_adaptive_pool 分配的对象

c++ - Barton-Nackman 与 std::enable_if

c++ - std::string 在第一次分配中不使用自定义分配器

MSVC 中的 C++ 自定义 STL 分配器错误?