我想知道是否有可能有如下行为的代码:
int main()
{
func<vector>(/*some arguments*/);
}
也就是说,我希望用户能够指定容器,而无需指定它所操作的类型。
例如,可能定义func
的一些(元)代码(不适用于上面的代码)如下所示:
template<typename ContainerType>
int func(/*some parameters*/)
{
ContainerType<int> some_container;
/*
operate on some_container here
*/
return find_value(some_container);
}
发布于 2016-07-05 18:25:21
语法是
template <template <typename...> class ContainerType>
int func(/*some parameters*/)
{
// Your code with ContainerType<int>
}
注意:typename
不能替换class
(在c++17之前)。
您不能简单地使用typename
而不是typename...
,因为std::vector
接受类型和分配器(默认值):std::vector<T, Allocator>
发布于 2016-07-05 18:28:04
试试这个:
template<template<typename,typename> class ContainerType>
int func (/*some parameters*/)
{
}
您需要两个内部模板参数,因为std::vector
定义为:
template < class T, class Alloc = allocator<T> > class vector;
https://stackoverflow.com/questions/38200959
复制相似问题