#include <cassert>
struct a
{
virtual ~a() {}
char a_[10];
};
struct b
{
virtual ~b() {}
char b_[20];
};
struct c : public a
{
virtual ~c() {}
char c_[15];
};
struct d : public b, a
{
virtual ~d() {}
char d_[5];
};
int main()
{
a a_;
c c_;
d d_;
a* a__ = &a_;
a* c__ = &c_;
a* d__ = &d_;
assert((void*)&a_ == (void*)a__);
assert((void*)&c_ == (void*)c__);
assert((void*)&d_ == (void*)d__); // error on most compiler
}
コンパイル時に 3 番目のアサーションを検出できるクラス継承グラフ間で void* キャストの安全性をテストする方法を探しています。
template<typename Base, typename Derived>
struct test
{
enum {
is_safe = (static_cast<Derived*>(static_cast<Base*>(nullptr)) == nullptr)
};
};
私の意図は上記のコードに記載されていますが、キャストは定数式ではないため、コンパイルされません。プラットフォーム/コンパイラに依存しない方法で確認することは可能ですか?