首页 > 解决方案 > 元编程:动态声明一个新结构

问题描述

是否可以动态声明一个新类型(一个空的 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()功能会很好。

现在有状态的元编程格式不正确,这样的事情可能吗?

标签: c++templatesmetaprogrammingstatefulcompile-time-constant

解决方案


你几乎可以得到你想要使用的语法

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);

推荐阅读