仅使用C++14实现类似mp-units downcasting facility的类型别名机制
可行实现方案(C++14 兼容)
完全基于C++14特性实现,无任何高版本依赖,编译期完成所有解析,无运行时开销,符合嵌入式场景使用要求:
#include <type_traits> namespace detail { // C++14 兼容实现 void_t template<typename... Ts> struct make_void { using type = void; }; template<typename... Ts> using void_t = typename make_void<Ts...>::type; // 正向映射表:基类型 -> 别名类型 template<typename Base, typename = void> struct downcast_map { static constexpr bool is_registered = false; }; // 反向映射表:别名类型 -> 基类型 template<typename Target, typename = void> struct downcast_reverse_map { static constexpr bool is_registered = false; }; // downcast 核心实现 template<typename T, typename = void> struct downcast_impl { using type = T; }; template<typename T> struct downcast_impl<T, void_t<typename downcast_map<T>::type>> { using type = typename downcast_map<T>::type; }; // downcast_base 核心实现 template<typename T, typename = void> struct downcast_base_impl { using type = T; }; template<typename T> struct downcast_base_impl<T, void_t<typename downcast_reverse_map<T>::type>> { using type = typename downcast_reverse_map<T>::type; }; } // namespace detail // 对外暴露接口 template<typename T> using downcast = typename detail::downcast_impl<T>::type; template<typename T> using downcast_base_t = typename detail::downcast_base_impl<T>::type; // 注册宏:完成基类型和别名的双向绑定,仅需调用一次 #define REGISTER_DOWNCAST(TargetAlias, BaseType) \ namespace detail { \ template<> struct downcast_map<BaseType, void> { \ static constexpr bool is_registered = true; \ using type = TargetAlias; \ }; \ template<> struct downcast_reverse_map<TargetAlias, void> { \ static constexpr bool is_registered = true; \ using type = BaseType; \ }; \ }
使用示例
// 冗长的基模板类型定义 template<int N, typename T> struct LongBaseTemplate { T val = N; }; // 自定义短别名 struct MyShortAlias : LongBaseTemplate<42, int> { // 可扩展别名特有逻辑,也可空实现 }; // 注册双向映射 REGISTER_DOWNCAST(MyShortAlias, LongBaseTemplate<42, int>); // 功能验证 int main() { // 正向解析验证 static_assert(std::is_same<downcast<LongBaseTemplate<42, int>>, MyShortAlias>::value, ""); // 未注册类型返回自身 static_assert(std::is_same<downcast<LongBaseTemplate<1, float>>, LongBaseTemplate<1, float>>::value, ""); // 反向解析验证 static_assert(std::is_same<downcast_base_t<MyShortAlias>, LongBaseTemplate<42, int>>::value, ""); // 非别名类型返回自身 static_assert(std::is_same<downcast_base_t<LongBaseTemplate<42, int>>, LongBaseTemplate<42, int>>::value, ""); return 0; }
方案说明
- 所有逻辑均在编译期完成,无运行时内存、性能损耗
- 仅需在别名定义完成后调用一次注册宏即可完成绑定,操作门槛低
- 完全满足要求的双向解析规则,未注册类型自动返回自身
- 兼容所有支持C++14标准的编译器,可直接在ARM嵌入式环境使用
内容的提问来源于stack exchange,提问作者KitsuneSan
相关产品推荐
相关产品推荐

