c++ - 元编程 : Declare a new struct on the fly

标签 c++ templates metaprogramming stateful compile-time-constant

是否可以即时声明新类型(空结构体或没有实现的结构体)?

例如

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() 函数会很好。

现在 stateful metaprogramming is ill-formed ?

最佳答案

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

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

关于c++ - 元编程 : Declare a new struct on the fly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55341859/

相关文章:

ruby-on-rails - 给观察者动态添加回调方法

c++ - 单例实现 : Is a namespace approach often preferable over a singleton class?

c++ - 将汇编指令翻译成 C++

c++ - 对枚举值进行模板化以选择句柄打开/关闭

c++ - 为什么我需要重新声明部分模板特化的方法/成员?

ruby - 如何使用 Ruby 的元编程来减少方法数

c++ - 不允许不完整的类型 : stringstream

c++ - 最小化数字 - c++

html - Rockettheme 模板侧边栏出现故障

c++ - 具有某种条件的宏