空结构或匿名结构作为标记

Empty struct or anonymous struct as tag

本文关键字:结构      更新时间:2023-10-16

标签类型定义为匿名空结构或空结构之间有什么区别吗?

using A = struct {};
struct B {};

在我看来,唯一的区别是"有效"类型名称,当人们使用一种反射(即 __PRETTY_FUNCTION__<cxxabi.h>:abi::__cxa_demangle(typeid().name())等)。

ADL 适用于两种方式:

namespace ns
{
using A = struct {};
struct B {};
constexpr
bool
adl(A)
{
    return true;
}
constexpr
bool
adl(B)
{
    return true;
}
}
template< typename type >
constexpr
bool
adl(type)
{
    return false;
}
static_assert(adl(ns::A{}));
static_assert(adl(ns::B{}));

除了您已经注意到的不同字符串之外,唯一显着的区别是您可以使用精心制作的类型说明符引用B,因此您可以说struct B b;而不是B b;但不能使用struct A a; A因为 typedef-name 而不是类名。

然而,几乎没有一个很好的理由说struct B而不仅仅是B所以在实践中,差异并不重要,尤其是对于标签类型。