0
#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)
    };
};

私の意図は上記のコードに記載されていますが、キャストは定数式ではないため、コンパイルされません。プラットフォーム/コンパイラに依存しない方法で確認することは可能ですか?

4

1 に答える 1

1

標準によれば、toからXtoへのキャストは、がと同じである場合にのみ明確に定義されます。他のすべては未定義の動作です。したがって、可能な唯一のポータブルで標準に準拠した定義は次のとおりです。void*void*YXYtest

template<typename Base, typename Derived>
struct test
{
    enum {
        is_safe = false;
    };
};

template <typename X>
struct test<X, X>
{
    enum {
        is_safe = true;
    };
};
于 2012-11-25T15:51:55.107 に答える