是否可以动态声明一个新类型(一个空结构,或一个没有实现的结构)?
EG
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;
但对于模板/ meta一些神奇的make_new_type()
函数会很好。
在C ++ 20中:
using A = decltype([]{}); // an idiom
using B = decltype([]{});
...
这是惯用的代码:这就是在C ++ 20中写一个“给我一个独特类型”的方式。
在C ++ 11中,最清晰,最简单的方法是使用__LINE__
:
namespace {
template <int> class new_type {};
}
using A = new_type<__LINE__>; // an idiom - pretty much
using B = new_type<__LINE__>;
匿名命名空间是最重要的一点。将new_type
类放在匿名命名空间中是一个严重的错误:这些类型在翻译单元中不再是唯一的。在您计划发货前15分钟,各种欢闹会随之而来:)
这扩展到C ++ 98:
namespace {
template <int> class new_type {};
}
typedef new_type<__LINE__> A; // an idiom - pretty much
typedef new_type<__LINE__> B;
另一种方法是手动链接类型,让编译器静态验证链接是否正确完成,如果不这样做,则弹出错误。所以它不会脆弱(假设魔法发挥作用)。
就像是:
namespace {
struct base_{
using discr = std::integral_type<int, 0>;
};
template <class Prev> class new_type {
[magic here]
using discr = std::integral_type<int, Prev::discr+1>;
};
}
using A = new_type<base_>;
using A2 = new_type<base_>;
using B = new_type<A>;
using C = new_type<B>;
using C2 = new_type<B>;
只需要一点点魔力就可以确保A2和C2类型的行不能编译。在C ++ 11中是否可以实现这种魔力是另一回事。
您几乎可以获得所需的语法
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风格宏的作品
#include <type_traits>
#define newType(x) \
struct type_##x {}; \
using x = type_##x;
newType(A)
newType(B)
newType(C)
int main ()
{
static_assert(!std::is_same<A, B>::value, "");
static_assert(!std::is_same<B, C>::value, "");
static_assert(!std::is_same<A, C>::value, "");
}