如何知道个人容器包了几层?

今天看到一个有趣的问题,请见下述例子:测试

cppvector<vector<int> > v2d;
vector<vector<vector<string>> > v3d;
vector<vector<vector<vector<double>>>> v4d;

若是给你 v2dv3d 或是 v4d,你如何求得它们所包裹的层数?3d


万能的模板又要上场了:code

cpptemplate<class Y> 
struct s
{
    enum {dims = 0};
};

template<class Y>
struct s<std::vector<Y>>
{
    enum {dims = s<Y>::dims + 1};
};

来测试一下吧:string

cppstd::vector<std::vector<double> > x;
int n = s<decltype(x)>::dims; // n == 2;

这都属于 “乍看不难,细思恐极,模板棒喝” 的典型工程问题。。。模板

PS:搞图形的同志们应该会用得上~class

相关文章
相关标签/搜索