c++ - 元编程:动态声明一个新结构
问题描述
是否可以动态声明一个新类型(一个空的 struct 或一个没有实现的 struct )?
例如
constexpr auto make_new_type() -> ???;
using A = decltype(make_new_type());
using B = decltype(make_new_type());
using C = decltype(make_new_type());
static_assert(!std::is_same<A, B>::value, "");
static_assert(!std::is_same<B, C>::value, "");
static_assert(!std::is_same<A, C>::value, "");
“手动”解决方案是
template <class> struct Tag;
using A = Tag<struct TagA>;
using B = Tag<struct TagB>;
using C = Tag<struct TagC>;
甚至
struct A;
struct B;
struct C;
但是对于模板/元一些魔术make_new_type()
功能会很好。
现在有状态的元编程格式不正确,这样的事情可能吗?
解决方案
你几乎可以得到你想要使用的语法
template <size_t>
constexpr auto make_new_type() { return [](){}; }
using A = decltype(make_new_type<__LINE__>());
using B = decltype(make_new_type<__LINE__>());
using C = decltype(make_new_type<__LINE__>());
这是可行的,因为每个 lambda 表达式都会产生唯一的类型。因此,对于其中的每个唯一值,<>
您都会得到一个不同的函数,该函数返回一个不同的闭包。
如果你引入一个宏,你就可以摆脱__LINE__
像这样的输入
template <size_t>
constexpr auto new_type() { return [](){}; }
#define make_new_type new_type<__LINE__>()
using A = decltype(make_new_type);
using B = decltype(make_new_type);
using C = decltype(make_new_type);
推荐阅读
- javascript - 返回字符串:基于 N 天的 'Days' 或 'Months' 或 'Years'
- amazon-web-services - 将临时密码配置为数字,密码配置为字母数字?
- azure - 如何使用一个公共 IP 映射两个 azure 应用程序?
- javascript - 如何根据javascript中的条件从数组中过滤对象
- python - 如何计算 Pandas 列中的特定单词?
- visual-studio - Unity2020.3.9f1c1 等待(03:29 忙)
- python - Python Selenium - Linux 上的缓慢 send_keys() 执行
- r - 为具有条件的日期创建过滤器
- google-chrome - chrome google 扩展程序将消息数据从后台发送到 ui
- ios - iOS中信号量导致的崩溃如何处理?