- 论坛徽章:
- 0
|
本帖最后由 幻の上帝 于 2010-12-22 16:30 编辑
求一个元编程实现的根据源类型在编译期选择策略的类型转换模板(C++03),具体需求如下:
1.对于非类类型引用/指针,使用static_cast;
2.对于非多态类的类类型引用/指针,使用static_cast;
3.对于安全的upcast(源类型是目标类型的派生类),使用static_cast;
4.对于非安全的upcast(源类型不是目标类型的派生类)或者非多态虚基类的downcast,产生编译错误;
5.对于源类型是目标类型(去除引用/指针)的虚基类的引用/指针的downcast,使用dynamic_cast;
6.对于其它的crosscast,使用dynamic_cast;
7.对于其它的downcast,使用类似boost::polymorphic_downcast的实现。
貌似过于复杂了……所以我实现不出来- -...
一个问题是不知道是不是有办法能在编译期确定是不是有虚基类……
附现有实现:
- namespace _impl
- {
- template<typename _type, typename _type2, bool _bIsPolymorphicClass>
- struct _general_cast_helper
- {
- inline static _type
- cast(_type2 s)
- {
- return dynamic_cast<_type>(s);
- }
- };
- template<typename _type, typename _type2>
- struct _general_cast_helper<_type, _type2, false>
- {
- inline static _type
- cast(_type2 s)
- {
- return static_cast<_type>(s);
- }
- };
- template<typename _type>
- struct _general_cast_helper<_type, _type, true>
- {
- inline static _type
- cast(_type s)
- {
- return s;
- }
- };
- template<typename _type>
- struct _general_cast_helper<_type, _type, false>
- {
- inline static _type
- cast(_type s)
- {
- return s;
- }
- };
- }
- /*!
- \brief 类型转换:源类型为多态类时同 dynamic_cast ,否则同 static_cast 。
- */
- template<typename _tDst, typename _tSrc>
- inline _tDst
- general_cast(_tSrc* s)
- {
- return _impl::_general_cast_helper<_tDst, _tSrc*,
- std::tr1::is_polymorphic<_tSrc>::value>::cast(s);
- }
- /*!
- \brief 类型转换:源类型为多态类时同 dynamic_cast ,否则同 static_cast 。
- */
- template<typename _tDst, typename _tSrc>
- inline const _tDst
- general_cast(const _tSrc* s)
- {
- return _impl::_general_cast_helper<_tDst, _tSrc*,
- std::tr1::is_polymorphic<_tSrc>::value>::cast(s);
- }
- /*!
- \brief 类型转换:源类型为多态类时同 dynamic_cast ,否则同 static_cast 。
- */
- template<typename _tDst, typename _tSrc>
- inline _tDst
- general_cast(_tSrc& s)
- {
- return _impl::_general_cast_helper<_tDst, _tSrc&,
- std::tr1::is_polymorphic<_tSrc>::value>::cast(s);
- }
- /*!
- \brief 类型转换:源类型为多态类时同 dynamic_cast ,否则同 static_cast 。
- */
- template<typename _tDst, typename _tSrc>
- inline const _tDst
- general_cast(const _tSrc& s)
- {
- return _impl::_general_cast_helper<_tDst, _tSrc&,
- std::tr1::is_polymorphic<_tSrc>::value>::cast(s);
- }
复制代码 |
|