I'm trying to write a struct to calculate the pointer offset between a base and a derived class as a constant expression in C++03. The code is as follows:
template <typename Base, typename Derived, typename Via = Derived>
struct OffsetToBase
{
static const std::ptrdiff_t val =
(const char*const)static_cast<Base*const>(static_cast<Via*const>((Derived*const)(1u << 7))) -
(const char*const)(1u << 7);
};
The code compiles in GCC, but not in clang and VC. The error produced by clang and VC basically says that the initializer is not a constant expression with clang further underlines the sub-expression (Derived*const)(1u << 7)
.
So, my question is what the standards say about this? And if the initializer does not qualify as a constant expression according to the standards, then what is the reasoning behind this?
UPDATE: For your interest, I've found these two discussions:
"Initializer element is not constant" error for no reason in Linux GCC, compiling C
About cast in integer constant expression (in standard C)
But I don't think the same rules apply to C++.
static_cast
works on pointers. Just do the subtraction after the conversion to integer. – Villainous