Pre-C++17 (pre constexpr if) you can implement the underlying logic using a trait and specialization
#include <cstddef>
#include <vector>
template <typename> struct vector_nested_layer_count {
static constexpr std::size_t value{0};
};
template <typename T> struct vector_nested_layer_count<std::vector<T>> {
static constexpr std::size_t value{1 + vector_nested_layer_count<T>::value};
};
Or, using std::integral_constant
:
#include <cstddef>
#include <type_traits>
#include <vector>
template <typename>
struct vector_nested_layer_count : std::integral_constant<std::size_t, 0> {};
template <typename T>
struct vector_nested_layer_count<std::vector<T>>
: std::integral_constant<std::size_t,
1 + vector_nested_layer_count<T>::value> {};
Apply either of these approaches and add a helper variable template:
template <typename T>
constexpr std::size_t vector_nested_layer_count_v{
vector_nested_layer_count<T>::value};
static_assert(vector_nested_layer_count_v<int> == 0);
static_assert(vector_nested_layer_count_v<std::vector<std::vector<int>>> == 2);
static_assert(
vector_nested_layer_count_v<std::vector<std::vector<std::vector<float>>>> ==
3);
If you're not happy with the idiomatic _v
helper variable template (as opposed to a function) you can implement the function as:
template <typename T> constexpr int get_vector_nested_layer_count() {
return vector_nested_layer_count_v<T>;
}
static_assert(get_vector_nested_layer_count<std::vector<std::vector<int>>>() ==
2);
static_assert(get_vector_nested_layer_count<
std::vector<std::vector<std::vector<float>>>>() == 3);
If you're at C++17 or beyond the constexpr if approach of the other answer is arguably neater, if you really want a function API for this kind of query trait (somewhat atypical in classic meta-programming).