我有一个关于模板模板参数的问题:
让我们考虑一下下面的类:
template<typename T, template<class, class=std::allocator<T> > class UnderlyingContainerType = std::vector>
class MyContainer
{
public:
T Value1;
T Value2;
UnderlyingContainerType<T> Container;
MyContainer() {}
/* methods implementation goes here */
};在这个例子中,MyContainer是一个容器,聊天使用一个底层的与STL兼容的容器来做任何事情。
将基础容器类型声明为模板模板参数,而不是常规的模板参数,可以方便地使用类MyContainer,例如:
MyContainer<int> MCV; //implicitly using vector
MyContainer<int, std::list> MCL; //no need to write std::list<int> thanks to the
//template template parameters现在,虽然这可以很好地处理大多数STL容器,例如std::vector、std::deque、std::list等等,但它不能用于c++11中提供的std::array。
原因是std::array具有不同于向量的模板参数签名。具体地说,它们是:
std::vector<class T, class allocator = std::allocator<T> >
std::array<class T, int N>我的问题是,是否有一种方法可以泛化类数组,以便底层容器也可以是std::MyContainer。
我要提前谢谢你。
发布于 2015-03-17 05:27:07
vector和array接口之间的共性仅限于元素类型。您的容器应该反映这一点:
template<typename T, template<typename> class underlying_container>
struct container
{
underlying_container<T> storage;
};现在的使用需要一个小技巧:
template<typename T> using vec = vector<T>;
template<typename T> using arr2 = array<T, 2>;注意,与vector不同,vec有一个固定的分配器,而arr2与array不同,它有一个固定的大小。
用法现在很简单:
container<int, vec> a;
container<double, arr2> b;或者,如果您希望将接口与vector使用的接口相匹配,只需为array添加一个模板别名来实例化大小,并添加一个未使用的类型参数:
template<typename T, typename> using arr2 = array<T, 2>;发布于 2015-03-17 06:59:23
我不知道怎样才能达到你想要的效果。但是如果你不需要编写MyContainer<int> MCV;的能力,你可以使用
template<class UnderlyingContainerType, class T = typename UnderlyingContainerType::value_type>
class MyContainer
{
public:
T Value1;
T Value2;
UnderlyingContainerType Container;
MyContainer() {}
/* methods implementation goes here */
};
int main() {
MyContainer<std::vector<int>> MCV{};
MyContainer<std::array<int, 5>> MCA{};
}它并不比MyContainer<int, std::vector> MCV;更适合输入
当然,您仍然可以为基于矢量的版本添加别名:
template<class T>
using MyContainerV = MyContainer < std::vector<T> > ;https://stackoverflow.com/questions/29086541
复制相似问题