Is it possible to create an inline function wrapper around "sizeof expression", which returns a signed number?
How would a wrapper function look like? It should work with all kind of expressions (C arrays, etc.), so it can be a one-for-one replacement of sizeof, but it returns a signed number.
So, basically, I'd like to have a ssizeof
, which returns a signed number, something like this:
constexpr std::ptrdiff_t ssizeof(X) {
return static_cast<std::ptrdiff_t>(sizeof(X));
}
So for example:
long a;
int b = 8;
// no signed/unsigned comparison warning here, because
// ssizeof(a) returns a signed number
if (ssizeof(a)<b) {
}
The solution is maybe not that simple, because of the automatic array->pointer decay rules (and maybe there could be other problems?).
If one-for-one replacement is not possible (because ssizeof
's parameter will always be evaluated), is it possible to do this, if evaluation is allowed?
ssizeof(int)
. How about using a macro for this? I know macro is bad in general, but in this case only#define SIZEOF(x) ...
seems to work. Apart from that the expression you pass to it, needs to be unevaluated as well butssizeof(f())
doesn't ensuref()
is unevaluated. – Toupeesizeof
is supposed to be unevaluating expression. – Hanover#define MY_SIZEOF(x) std::ptrdiff_t(sizeof(x))
– Honeysizeof()
is not a function. – Colicrootconstexpr const ::std::ptrdiff_t s(::std::size_t const size) noexcept{ return(static_cast<::std::ptrdiff_t>(size)); } auto x = s(sizeof(4 + 4.0));
– Hanovercontainer.size()
. – Faciessizeof expression
without a macro. If you are going to use a macro, you just can#define ssizeof (ssize_t)sizeof
and call it a day. – Maenadsize_t
forsize()
, but I have my own containers, which returns a signedsize()
). This short CppCon presentation tells my standpoint pretty well: youtube.com/watch?v=wvtFGa6XJDU – Binatefor (unsigned i=0; i<s-1; i++)
, ifs
is zero, then bad things happen. In the 32-bit world, there is no disadvantage of using signed numbers in my opinion, that's why I use them, I have no problems at all. The last thing which bothers me is sizeof (not a huge problem, I can live with it, I rarely use this operator) – Binatefor (unsigned i=0; i+1<s; i++)
problem solved. " I have no problems at all" you should make your mind, you have no problems at all or sizeof is not a huge problem. – Colicroot