STL容器作为模板参数 [英] STL container as a template parameter
问题描述
我正在尝试将STL容器作为模板参数传递.在这种情况下,就是向量.
I'm trying to pass an STL container as a template parameter. In this case, the vector.
这是我无法运行的代码:
Here is my not-functional code:
template<template<class> class TContainer, class TObject>
class Foobar
{
public:
explicit Foobar( TContainer<TObject*> & container )
:
container_( container ){}
private:
TContainer<TObject*> & container_;
};
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<IUnknown*> v;
Foobar<std::vector, IUnknown*> bla( v );
return 0;
}
这是我要执行的所有操作,因为编译器无法吞并此内容吗?
Is this, what I'm trying to do possible at all, because the compiler cannot swallow this?
推荐答案
您的代码有几处错误,这是一个有效的示例:
There are several things wrong with your code, here is a working example:
template<template<class, class> class TContainer, class TObject>
class Foobar
{
public:
explicit Foobar( TContainer<TObject*, std::allocator<TObject*>> & container )
:
container_( container ){}
private:
TContainer<TObject*, std::allocator<TObject*>> & container_;
};
int main()
{
std::vector<IUnknown*> v;
Foobar<std::vector, IUnknown> bla( v );
}
您的代码的主要缺陷是 std :: vector
带有两个模板参数.看起来像这个 template< class T,class Allocator = std :: allocator< T>类向量;
.另外, Joachim Pileborg 对于双指针问题 IUnknown **
是正确的.但是,您可以使用以下代码简化代码:
The main fault of your codes it that std::vector
takes two template arguments.
It looks like this template<class T, class Allocator = std::allocator<T>> class vector;
. Also, Joachim Pileborg is right about the double pointer issue, IUnknown**
.
However, you could simplify your code with the following:
template<class TContainer>
class Foobar
{
public:
explicit Foobar( TContainer & container )
:
container_( container ){}
private:
TContainer & container_; // Be careful with reference members
};
int main()
{
std::vector<IUnknown*> v;
Foobar<std::vector<IUnknown*>> bla( v ); // C++11 decltype(v) could be used
}
这篇关于STL容器作为模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!