[英]Will the template argument's destructor to a templated class be called on deletion?
[英]How to pass a templated class without it's argument list as a template argument?
#include <iostream>
template <typename T>
class Container1
{
// some implementation.
};
template <typename T>
class Container2
{
// some implementation.
};
template <typename type, typename container>
class CreateContainer
{
container<type> createContainer()
{
return container<type>();
}
container<const type> createConstContainer()
{
return container<const type>();
}
};
int main()
{
// doesn't compile.
CreateContainer<int, Container1> createContainer1;
CreateContainer<int, Container2> createContainer1;
// don't wanna do that:
// CreateContainer<Container2<int>, Container2<const int>, int> createContainer1;
// I might need to know the type inside the container (the int) so it's passed as well.
}
考虑这段代码,我正在创建一个工厂 class ,只要容器具有 const 元素,它就会创建一个普通容器。 那只是一个例子。 我实际上在做的是我想将一个迭代器返回到某个容器,并将一个 const 迭代器返回到同一个容器。 但是大部分代码与问题无关,所以我做了一个例子。 我想将容器作为模板参数传递,然后在工厂 class 中指定要传递给容器的 arguments 的内容。 如果我不传递没有参数列表的容器,我将不得不传递容器内部的类型、普通容器类型和工厂参数列表中的 const 容器类型 class 是多余的。
您可以将container
设为模板模板参数,并在main
中声明createContainer1
两次。 这编译:
#include <iostream>
template <typename T>
class Container1 {};
template <typename T>
class Container2 {};
template <typename type, template<class> class container>
class CreateContainer
{
container<type> createContainer()
{
return container<type>();
}
container<const type> createConstContainer()
{
return container<const type>();
}
};
int main()
{
CreateContainer<int,Container1> createContainer1;
CreateContainer<int,Container2> createContainer2;
}
请注意,这假定container
模板参数具有单个类型参数。 它不适用于例如template <typename T,size_t foo> struct container3 {};
,但如果您需要,它可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.