不指定内部类型的模板模板参数
Template template parameters without specifying inner type
我想知道是否有可能拥有具有以下行为的代码:
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);
}
语法是
template <template <typename...> class ContainerType>
int func(/*some parameters*/)
{
// Your code with ContainerType<int>
}
注意:class
不能替换为 typename
(直到 c++17)。
你不能简单地使用 typename
而不是 typename...
因为 std::vector
采用类型和分配器(默认):std::vector<T, Allocator>
试试这个:
template<template<typename,typename> class ContainerType>
int func (/*some parameters*/)
{
}
您需要两个内部模板参数,因为 std::vector
定义为:
template < class T, class Alloc = allocator<T> > class vector;
我想知道是否有可能拥有具有以下行为的代码:
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);
}
语法是
template <template <typename...> class ContainerType>
int func(/*some parameters*/)
{
// Your code with ContainerType<int>
}
注意:class
不能替换为 typename
(直到 c++17)。
你不能简单地使用 typename
而不是 typename...
因为 std::vector
采用类型和分配器(默认):std::vector<T, Allocator>
试试这个:
template<template<typename,typename> class ContainerType>
int func (/*some parameters*/)
{
}
您需要两个内部模板参数,因为 std::vector
定义为:
template < class T, class Alloc = allocator<T> > class vector;