In C++ sizeof
is somewhat unique in that it\'s legal to write this:
int x;
sizeof(x); // a variable
As well as simply:
<
Not considering macros and without decltype
, it is simply not possible because of the language syntax.
However you can get pretty damn close:
template
constexpr auto bitsof(T) { return sizeof(T) * CHAR_BIT; }
template <>
constexpr auto bitsof(int_12_bit) { return 12; }
template
constexpr auto bitsof() { return sizeof(T) * CHAR_BIT; }
template <>
constexpr auto bitsof() { return 12; }
auto test()
{
constexpr int a{};
constexpr int_12_bit x{};
static_assert(bitsof(a) == 32);
static_assert(bitsof(x) == 12);
static_assert(bitsof() == 32);
static_assert(bitsof() == 12);
}
Aside from the slightly different syntax (but c'mon it's so close it shouldn't really matter) the biggest difference to the sizeof
is that the arguments are not in an unevaluated context. So bitsof(foo())
will call foo()
. And bitsof(a)
is UB if a
is uninitialized.