C ++模板模板(双模板?)
|
我想构建一个“ 0”类,以便用户能够选择要用于实现“ 0”的容器。例如,
List/Vector
。
部分代码:
栈
#ifndef STACK_H_
#define STACK_H_
template <typename T, template<typename T> class ContainerType>
class Stack{
ContainerType<T> container;
public:
Stack() : container(ContainerType<T>()){}
};
#endif /* STACK_H_ */
测试文件
#include \"stack.h\"
#include <vector>
int main(){
Stack<int, std::vector<int> > stack;
return 0;
}
好吧,它无法编译。我在网上收到下一个错误:
Stack<int, std::vector<int> > stack;
错误:
expected a class template, got `std::vector<int, std::allocator<int> >\' test.cpp
invalid type in declaration before \';\' token test.cpp
type/value mismatch at argument 2 in template parameter
list for `template<class T, template<class T> class ContainerType>
class Stack\' test.cpp
没有找到相关结果
已邀请:
4 个回复
糕泰灌
,而没有别的,因为
驻留在ѭ9and命名空间中,并且您要输入模板template参数,而
不再是模板。接下来,“ 7”实际上需要两个模板参数,一个用于类型,另一个用于分配器:
现在,这仅启用具有两个模板参数作为基础类型的容器,因此您最好使用标准的功能:将其作为普通类型:
为确保基础类型具有相同的“ 14”,您可以执行伪造的“静态声明”,或者如果您具有启用了C ++ 0x的编译器,则可以执行实际的静态声明:
之所以起作用,是因为如果
与使用的容器的
不同,它将是
,并且可能不存在负大小的数组,这会导致编译器错误。 :)现在,使用C ++ 0x,您只需
即可:
为了方便起见,您现在可以为常见情况指定默认的模板参数:
现在,您可以只使用
来做到这一点(尽管它使用
作为基础类型)。 :)
搁手
(标准STL内部typedef)以获取该值。
然后,您可以简单地将其用作
,其中将包含
。
掸牛浓疗
命名空间,因此必须对其进行限定。但是除此之外,由于
是模板模板参数,您需要传递模板而不是最终类型:
师埠女
应该:
或者您可以在
之前加上前缀