C ++:可以在编译时检测到虚拟继承吗? [英] C++: Can virtual inheritance be detected at compile time?
问题描述
我想在编译时确定是否可以在没有dynamic_cast的情况下将指向Derived的指针强制转换为指向Base的指针.使用模板和元编程可能吗?这与确定Base是否是Derived的虚拟基类不是完全相同的问题,因为Base可能是Derived的虚拟基类的超类.
谢谢,提姆更新:我对这种方法感觉很好:
#include< iostream>使用命名空间std;Foo类{};酒吧:公共Foo{};Baz类别:公共虚拟Foo{};Autre类:公共虚拟酒吧{};typedef char Small;类Big {char dummy [2];};模板<类型名B,类型名D>struct is_static_castable{const B * foo;字符栏[1];静态小测试(char(*)[sizeof(static_cast< const D *>(foo))== sizeof(const D *)]));静态大测试(...);枚举{value =(sizeof(test(& bar))== sizeof(Small))};};int main(){cout<<"Foo-> Bar:"<<is_static_castable< Foo,Bar> :: value<<"\ n";cout<<"Foo-> Baz:"<<is_static_castable< Foo,Baz> :: value<<"\ n";cout<<"Foo-> Autre:"<<is_static_castable< Foo,Autre> :: value<<"\ n";}
但是它不适用于gcc:
multi-fun.cpp:在"is_static_castable< Foo,Baz>"的实例中:multi-fun.cpp:38:从此处实例化multi-fun.cpp:29:错误:无法通过虚拟基础"Foo"从基础"Foo"转换为派生类型"Baz"multi-fun.cpp:29:错误:数组绑定不是整数常量multi-fun.cpp:在"is_static_castable< Foo,Autre>"的实例中:multi-fun.cpp:39:从此处实例化multi-fun.cpp:29:错误:无法通过虚拟基础"Bar"从基础"Foo"转换为派生类型"Autre"multi-fun.cpp:29:错误:数组绑定不是整数常量
我对使用sizeof()技巧可以做什么感到困惑吗?
一次,我遇到了同样的问题.不幸的是,我对虚拟问题不太确定.但是:Boost有一个名为 But it doesn't work with gcc: Am I confused about what can be done with the sizeof() trick? I had the same problem, once. Unfortunately, I'm not quite sure about the virtual-problem. But: Boost has a class named Furthermore, there's a class 这篇关于C ++:可以在编译时检测到虚拟继承吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! is_base_of
的类(请参见multi-fun.cpp: In instantiation of ‘is_static_castable<Foo, Baz>’:
multi-fun.cpp:38: instantiated from here
multi-fun.cpp:29: error: cannot convert from base ‘Foo’ to derived type ‘Baz’ via virtual base ‘Foo’
multi-fun.cpp:29: error: array bound is not an integer constant
multi-fun.cpp: In instantiation of ‘is_static_castable<Foo, Autre>’:
multi-fun.cpp:39: instantiated from here
multi-fun.cpp:29: error: cannot convert from base ‘Foo’ to derived type ‘Autre’ via virtual base ‘Bar’
multi-fun.cpp:29: error: array bound is not an integer constant
is_base_of
(see here) which would enable you to do smth. like the followingBOOST_STATIC_ASSERT((boost::is_base_of<Foo, Bar>::value));
is_virtual_base_of
in Boost's type_traits
, maybe that's what you're looking for.