请考虑以下声明:
vector<vector<int> > v2d;
vector<vector<vector<string>> > v3d;
Run Code Online (Sandbox Code Playgroud)
如何在后续代码中找出向量的"维度"?例如,v2d为2,v3d为3?
Bat*_*eba 57
这些方面的东西:
template<class Y>
struct s
{
enum {dims = 0};
};
template<class Y>
struct s<std::vector<Y>>
{
enum {dims = s<Y>::dims + 1};
};
Run Code Online (Sandbox Code Playgroud)
然后例如,
std::vector<std::vector<double> > x;
int n = s<decltype(x)>::dims; /*n will be 2 in this case*/
Run Code Online (Sandbox Code Playgroud)
具有吸引力的特性,所有评估都在编译时.
Nik*_*iki 18
你可以这样做:
template<typename T>
int getDims(const T& vec)
{
return 0;
}
template<typename T>
int getDims(const vector<T>& vec)
{
return getDims(T{})+1;
}
Run Code Online (Sandbox Code Playgroud)
旁注:此数量有时称为" 排名 ".