【发布时间】:2020-09-12 17:06:34
【问题描述】:
我希望能够根据派生类中数据成员的数量将基类中数据成员的类型设置为尽可能小。因此,如果派生类的数据成员数为5,则基类的数据成员类型应为std::uint8_t。
这是我已经尝试过的:
#include <iostream>
template <std::size_t N>
struct min {
using type = typename std::conditional_t<
(N <= 8), std::uint8_t,
typename std::conditional_t<
(N <= 16), std::uint16_t,
typename std::conditional_t<
(N <= 32), std::uint32_t, std::uint64_t
>
>
>;
};
template <std::size_t N>
using min_t = typename min<N>::type;
template <typename CrtpT, typename T = min_t<CrtpT::end__ - CrtpT::begin__ + 1>>
struct Wrapper {
T a;
};
struct Foo : Wrapper<Foo> {
static constexpr int begin__ = __LINE__;
static constexpr int F_A = 0;
static constexpr int F_B = 0;
static constexpr int F_C = 0;
static constexpr int end__ = __LINE__;
};
int main() {
Foo foo;
std::cout << static_cast<unsigned>(foo.a) << std::endl;
return 0;
}
这显然不起作用并且无法编译,因为在 Wrapper 类定义时没有完全指定 Foo 类。
有没有人对如何做到这一点有更好的想法,或者有可能吗?
提前致谢!
【问题讨论】:
-
无关的,像
begin__这样的名字是为实现保留的。 -
看来您需要反思。当前的解决方案,即使你让它工作,如果你在
Foo中添加空行,也会失败。 -
没有冒犯,但在我看来 XY 有问题。
-
@cigien 是的,我知道只是没有改变它
-
@StoryTeller-UnslanderMonica 我知道有人会告诉我 :) ... 这是我目前正在开发的小型图书馆:github.com/m-peko/bitflags。我试图避免指定每个标志的数据类型