Reputation: 2652
In C++, you can prevent a function from being used on T
using the = delete
syntax. You can't call sizeof
using an incomplete type.
However, I was wondering, is there a way to prevent sizeof
from being used on a complete type?
My initial attempts went something like this:
size_t operator sizeof(T) = delete;
Which obviously didn't work.
Now, from research online, I wasn't able to find anything suggesting that it was possible to prevent sizeof
from being used on a type, unless that type was incomplete.
So, is there any way to prevent the sizeof
operator from being used with a class (either using the = delete
syntax or otherwise), that results in a compile-time error?
Anything is appreciated, no matter how hacky, and a solution that works most of the time is fine, too. C++14 compatible and no external libraries, though.
Upvotes: 0
Views: 185
Reputation: 24177
Unlikely. sizeof is not a function, it's a builtin operator. As it's necessary under the hood for the correct behavior of new (memory size to allocate for some object), I can't see how you could remove it.
But if the goal is to hide implementation size you could add some indirection layer and hide the actual type behind some facade of fixed size, but it wouldn't be a zero cost abstraction.
Upvotes: 3