C++ 默认值未知的模板参数
我有一个模板函数,它将容器作为参数 (我对vector、set和map都使用此函数,因此尝试避免此操作将花费大量代码复制) 因此,我自然宣布:C++ 默认值未知的模板参数,c++,templates,C++,Templates,我有一个模板函数,它将容器作为参数 (我对vector、set和map都使用此函数,因此尝试避免此操作将花费大量代码复制) 因此,我自然宣布: template<template<class T, class Allocator = std::allocator<T>> class Container> Container<std::weak_ptr<A>>* Foo() {...} 在这种情况下,分配器的默认值与Foo-std::
template<template<class T, class Allocator = std::allocator<T>> class
Container> Container<std::weak_ptr<A>>* Foo() {...}
在这种情况下,分配器的默认值与Foo
-std::allocator
与std::allocator
定义中的值不同
长话短说,我需要将它发送到Foo
一个容器,其中包含第二个参数,可以在不知道默认类型的情况下进行默认设置(因此此函数模板可以用于map、vector或基本上任何其他容器)。这可能吗
编辑:我不能以任何方式使用C++11,编译器是gcc 4.1.2(我无法控制)在C++11中,您可以使用任何模板作为模板参数:
template<template <class ...> class Container>
Container<std::weak_ptr<A>>* Foo() {...}
模板
容器*Foo(){…}
这里有一个关于模板参数如何操作的误解。本声明:
template<template<class T, class Allocator = std::allocator<T>> class Container>
Container<std::weak_ptr<A>>* Foo() {...}
template < template <class, class> class Container>
Container<std::weak_ptr<A>>* Foo() {...}
它不适用于,因为它接受四个模板类型参数:
template<
class T,
class Allocator = std::allocator<T>
> class vector;
template<
class Key,
class T,
class Compare = std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, T> >
> class map;
template < template <class...> class Container>
Container<std::weak_ptr<A>>* Foo() {...}
模板<
类密钥,
T类,
类比较=标准::更少,
类分配器=std::分配器
>类图;
在C++11中,可以对函数进行泛化,使模板参数接受任意数量的模板类型参数:
template<
class T,
class Allocator = std::allocator<T>
> class vector;
template<
class Key,
class T,
class Compare = std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, T> >
> class map;
template < template <class...> class Container>
Container<std::weak_ptr<A>>* Foo() {...}
template
容器*Foo(){…}
但是,这永远不会起作用,因为某些容器类型不能仅使用单个模板参数(例如,
map
)构造 我找到了一个解决方案,它并不优雅,但很有效:
将另一个模板参数发送到Foo
,该模板参数将是解除分配器故障的方法:
template<template<typename> class DefaultAllocator, template<typename T,
typename Allocator = DefaultAllocator<T>> class Container>
Container<std::weak_ptr<A>>* Foo() {...}
模板
容器*Foo(){…}
通过这种方式,我仍然发送Foo
。
另外,通过创建一些包装器
模板类MapAllocatorWrapper:std::allocator
,我可以在std::weak_ptr
中发送foo什么是A
?OP在他的问题中使用了这种类型。我刚刚添加了我不能使用C++11,我希望我能:)在弱ptr
中A
是什么?我相信您尝试的内容过于冗长,可能对于一个更简单的操作来说过于复杂。无论如何,您的问题当然是由以下事实引起的:容器具有不同的参数:。我不会写这样的代码(以它为例)@MarcoA。当我将地图和集合包装在某个类中时,它们都符合相同的模板:template OP必须处理其方法中更基本的问题。向量
、列表
、设置
和映射
的模板参数不能在Foo
中使用Allocator
是vector
和list
的第二个模板参数。这是set
的第三个参数。这是map
的第四个参数;我定义了一个从std::map继承的特定类型,该类型仅使用2个模板参数,并且使用该类型存在问题;因为我在Foo的定义中使用了默认参数,所以我必须为它设置一个默认值(否则编译器会尖叫),问题是我是否可以在不指定默认类型的情况下执行此操作。