Reputation: 38919
Given a typedefined 2-dimensional array:
typedef float Matrix3x3[3][3];
If I want to get the total number of float
s in Matrix3x3
I feel like I should be able to just do:
sizeof(Matrix3x3) / sizeof(**Matrix3x3)
But obviously I cannot dereference a type. What is the best way to do this?
Upvotes: 1
Views: 134
Reputation: 96053
Since it's C++ rather than C, I would write a proper type trait:
#include <cstddef>
#include <type_traits>
template <typename T>
inline constexpr std::size_t total_extent_v = 1;
template <typename T, std::size_t N>
inline constexpr std::size_t total_extent_v<T[N]> = N * total_extent_v<T>;
Usage:
std::cout << total_extent_v<Matrix3x3> << '\n';
If this is too much and you want something simpler, I would use a std::remove_all_extents_t
-based solution as suggested by @StoryTeller.
Upvotes: 2
Reputation: 170055
You can use std::remove_all_extents
.
sizeof(Matrix3x3) / sizeof(std::remove_all_extents_t<Matrix3x3>)
It's a trait that essentially removes all the square brackets from the array type, no matter how many dimensions.
Upvotes: 4
Reputation: 62563
First of all, you want to divide, not multiply. Second of all, customary way would be
auto n_elements = sizeof(Matrix3x3) / sizeof(std::declval<Matrix3x3>()[0][0]);
That gives expected value of 9
.
Upvotes: 2