我会模板化一个函数,以便将它与vector,set或STL的任何其他容器一起使用(具有正确的API ...)
我的函数当前原型是:
vector<vector<int>> f ( const vector<int> & v, int size ) {...}
我尝试了不同类型的声明,如下所示:
template<template<typename U, typename Alloc> class C, typename T>
C<C<T, Alloc>, Alloc> f (const C<T, Alloc>& v, int size)
{...}
但是我找不到正确的写法。你能救我吗?
答案 0 :(得分:3)
尝试
template<template<typename...> class C1, template<typename...> class C2, typename T, typename... Args>
C1<C2<T, Args...>> f (const C2<T, Args...>& v, int size)
{...}
允许不同的容器或
template<template<typename...> class C, typename T, typename... Args>
C<C<T, Args...>> f (const C<T, Args...>& v, int size)
{...}
如果内部和外部容器需要相同或者只是:
template<template<typename...> class C, typename T>
C<T> f (const T& v, int size)
并在上面的第一个示例中访问T::value_type
而不是T
。
很难提供更好的建议,因为用例不清楚你的问题。
更新:解释您的尝试无效的原因:
template<template<typename U, typename Alloc> class C, typename T>
C<C<T, Alloc>, Alloc> f (const C<T, Alloc>& v, int size)
{...}
查看它并再次思考:首先,您需要Alloc
作为另一个参数,因为模板模板参数中的参数名称不能用于任何事情。这将导致:
template<template<typename T_dummy, typename A_dummy> class C, typename T, typename Alloc>
C<C<T, Alloc>, Alloc> f (const C<T, Alloc>& v, int size)
{...}
更好,但现在你有一个真正的问题:内部容器的分配器类似于
std::allocator<int>
适用于内部容器,但不适用于需要
行的外部容器std::allocator<std::vector<int>>
因此,尝试重新使用外部容器的内部分配器注定要失败。
答案 1 :(得分:1)
您可能需要:
template<template <typename, typename> class Container, typename T, typename Alloc>
Container<Container<T, Alloc>, typename Alloc::template rebind<Container<T, Alloc> >::other>
f(const Container<T, Alloc> & v, int size ) {
// Your implementation
//return {{}};
}
正如Daniel Frey所说,内外容器的分配器不能相同,
所以在代码rebind
以上的分配器是正确的。