此模板能够存储特定类型的矢量迭代器。
template<typename T>
struct foo
{
typedef typename std::vector<T>::iterator it;
std::vector<it> m_collection;
};
如何使模板更加通用并支持其他std集合迭代器(std::list
,std::deque
等)?
答案 0 :(得分:0)
如何使模板更具通用性并支持其他std集合迭代器(列表,双端队列等)?
是否要将容器作为模板参数传递?
那是:您在寻找模板模板参数吗?
template <template <typename...> class C, typename T>
struct foo
{
typedef typename C<T>::iterator it;
std::vector<it> m_collection;
};
可用如下
foo<std::vector, int> fvi;
foo<std::set, long> fsl;
或者也许
template <template <typename...> class C, typename ... Ts>
struct foo
{
typedef typename C<Ts...>::iterator it;
std::vector<it> m_collection;
};
那么您还可以将其用于地图吗?
foo<std::map, int, std::string> fmis;
foo<std::unordered_map, long, char> fulc;
不幸的是,该解决方案与std::array
不兼容,它需要一个非模板参数。
或者也许您想像通过专业化那样传递类型并选择容器和包含的类型?
template <typename>
struct foo;
template <template <typename...> class C, typename ... Ts>
struct foo<C<Ts...>>
{
typedef typename C<Ts...>::iterator it;
std::vector<it> m_collection;
};
因此您可以按以下方式使用它
foo<std::vector<int>> fvi;
foo<std::set<long>> fsl;
foo<std::map<int, std::string>> fmis;
foo<std::unordered_map<long, char>> fulc;
,还为std::array
template <template <typename, std::size_t> class A,
typename T, std::size_t N>
struct foo<A<T, N>>
{
typedef typename A<T, N>::iterator it;
std::vector<it> m_collection;
};
或者,也许
template <typename T>
struct foo
{
typedef typename T::iterator it;
std::vector<it> m_collection;
};
没有推论容器和包含类型吗?
答案 1 :(得分:0)
这是一个最小的运行示例,其中foo
可以在序列容器之间切换以存储it
:
#include <vector>
#include <deque>
#include <list>
template
<
typename T,
template<typename, typename> class SequenceContainer,
template <typename> class Allocator = std::allocator
>
struct foo
{
typedef typename SequenceContainer<T, Allocator<T>>::iterator it;
SequenceContainer<it, Allocator<it>> m_collection;
};
using namespace std;
int main()
{
foo<double, vector> vecFoo;
foo<double, deque> dequeFoo;
foo<double, list> listFoo;
return 0;
};