![](/img/trans.png)
[英]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.