I have a function that takes a multidimensional std::vector
and requires the depth (or the number of dimensions) to be passed in as a template parameter. Instead of
You can define the following class template vector_depth<>
which matches any type:
template
struct vector_depth {
static constexpr size_t value = 0;
};
This primary template corresponds to the base case that ends the recursion. Then, define its corresponding specialization for std::vector
:
template
struct vector_depth> {
static constexpr size_t value = 1 + vector_depth::value;
};
This specialization matches an std::vector
and corresponds to the recursive case.
Finally, define the function template, GetDepth()
, that resorts to the class template above:
template
constexpr auto GetDepth(T&&) {
return vector_depth>>::value;
}
Example:
auto main() -> int {
int a{}; // zero depth
std::vector b;
std::vector> c;
std::vector>> d;
// constexpr - dimension determinted at compile time
constexpr auto depth_a = GetDepth(a);
constexpr auto depth_b = GetDepth(b);
constexpr auto depth_c = GetDepth(c);
constexpr auto depth_d = GetDepth(d);
std::cout << depth_a << ' ' << depth_b << ' ' << depth_c << ' ' << depth_d;
}
The output of this program is:
0 1 2 3