我想要一个嵌套类
B
,其行为如下:
如果
T
是void
,那么B
只有一个成员字段sz
和sizeof(B) == sizeof(sz)
否则,
B
有一个成员字段sz
并以某种方式获得T
#include <iostream>
#include <type_traits>
template <typename T>
class A {
struct B {
size_t sz;
if (T != void)
T t; // declare T field
};
};
我找到了这个部分解决方案,但它仅适用于整数类型,并且在访问
T
数据时有一些不便。
static constexpr bool is_void = std::is_same_v<void, T>;
using type = std::conditional_t<is_void, bool, T>;
struct B {
size_t sz;
type : (is_void ? 0 : sizeof(type));
// if 'type' has a name, possible CE: Named bit-field has zero width
};
或者,我们可以使用继承技巧创建类似的东西,但我想找到语言提供的其他方法(无样板代码)(〜专门为这种情况创建)。
struct empty_class {};
struct container { T t; }; // solve std::is_class_v<T> && !std::is_final_v<T>
static constexpr bool is_void = std::is_same_v<void, T>;
using base = std::conditional_t<is_void, empty_class, container>;
struct B : base {
size_t sz;
};
您可以简单地将
A
专门化为 void
:
template <typename T>
class A {
struct B {
size_t sz;
T t;
};
};
template <>
class A<void> {
struct B {
size_t sz;
};
};