是否可以即时声明新类型(空结构体或没有实现的结构体)?
例如
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);
关于c++ - 元编程 : Declare a new struct on the fly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55341859/