小编Tim*_*Tim的帖子

C++:可以在编译时检测虚拟继承吗?

我想在编译时确定是否可以从没有dynamic_cast <>的指针转换为指向Derived的指针.这可能使用模板和元编程吗?这与确定Base是否是Derived的虚拟基类不完全相同,因为Base可能是Derived虚拟基类的超类.

谢谢Tim更新:我觉得这个方法很好:

#include <iostream>

using namespace std;

class Foo
{
};

class Bar : public Foo
{
};

class Baz : public virtual Foo
{
};

class Autre : public virtual Bar
{
};

typedef char Small;
class Big { char dummy[2]; };

template<typename B, typename D>
struct is_static_castable
{
    const B* foo;
    char bar[1];
    static Small test(char(*)[sizeof(static_cast<const D*>(foo)) == sizeof(const D*)]);
    static Big test(...);
    enum { value = (sizeof(test(&bar)) == sizeof(Small)) };
};

int main()
{

    cout << …
Run Code Online (Sandbox Code Playgroud)

c++ templates

22
推荐指数
2
解决办法
2943
查看次数

标签 统计

c++ ×1

templates ×1