繁体   English   中英

如何将指向基类成员的指针强制转换为指向派生类的同一成员的指针

[英]How to cast a pointer to member of base class to a pointer to the same member of derived class

请考虑以下示例:

struct foo {
    int bax;
};

struct fuu : foo {
};

template<int foo::*>
struct tox {};

template<int fuu::*>
struct tux {};

int foo::* xo = &foo::bax;
int fuu::* xu = &fuu::bax;   // works

typedef int foo::*boz;

typedef tox<&foo::bax> qox;
typedef tux<&fuu::bax> qux; // fails: 'int foo::*' cannot be converted to a value of type 'int fuu::*'
typedef tux<(boz)&fuu::bax> qux; // fails: non-type template argument of type 'boz' (aka 'int foo::*') cannot be converted to a value of type 'int fuu::*'

此示例也可在http://coliru.stacked-crooked.com/a/15f3e7acd8de04a3获得 ,clang ++和g ++都会产生相同的错误。

如何投射fuu :: bax所以它被模板tux接受?

不幸的是,我认为还没有办法做到这一点。 有关此问题的公开缺陷报告 您将不得不以某种方式解决它,例如更改tux以使其接受int foo::* ,或添加另一个模板参数:

template <typename T, int T::* arg>
struct tux {
    static_assert(std::is_convertible<int T::*, int fuu::*>::value,
                  "T must be an unambiguous accessible base of fuu");
    // note that this still works
    // however, you won't be able to use it as a template argument
    static constexpr int fuu::* pm = arg;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM