gpt4 book ai didi

c++ - 使用 C++ 模板编译类成员变量?

转载 作者:搜寻专家 更新时间:2023-10-30 23:55:15 26 4
gpt4 key购买 nike

我有一个类似于此的类:

class Compound
{
void* pValue0;
void* pValue1;
void* pValue2;
void* pValue3;
void* pValue4;
void* pValue5;
void* pValue6;
void* pValue7;
void* pValue8;
void* pValue9;
void* pValueA;
void* pValueB;
void* pValueC;
};

当我创建一个新的 Compound 类时,我分配了额外的内存 [sizeof(Compound) + extraSpace]。每个 pValue 都指向额外内存中的一个地址。

现在,我想根据需要减少 pValue 的数量。模板似乎很合适。

因此,如果我想要一个类 Compound<0A>,我只需要 pValue0 和 pValueA,然后让编译器删除所有其他 pValue。本质上,我希望它变成:

template <uint Mask = 0A>
class Compound<Mask>
{
void* pValue0;
void* pValueA;
}

这可能吗?我接近 enable_if,但是当我试图将它限制为特定掩码时,编译器会抛出有关在 enable_if 情况为假时无法找到类型的错误。

谢谢大家!

最佳答案

这可能会:

template<char...>
struct flags_tag {constexpr flags_tag(){}; };

template<char...Cs>
struct make_flags{ using type=flags_tag<Cs...>; };
template<char...Cs>
struct make_flags<'0','x',Cs...>:make_flags<Cs...>{};
template<char...Cs>
struct make_flags<'0','X',Cs...>:make_flags<Cs...>{};
template<char...Cs>
using make_flags_t = typename make_flags<Cs...>::type;

template<char...Cs>
constexpr make_flags_t<Cs...> operator""_flag(){ return {}; }

template<char> struct pValue_t;
template<> struct pValue_t<'0'>{ void* pValue0 = 0; };
template<> struct pValue_t<'1'>{ void* pValue1 = 0; };
// ...
template<> struct pValue_t<'A'>{ void* pValueA = 0; };
template<> struct pValue_t<'B'>{ void* pValueB = 0; };
template<> struct pValue_t<'C'>{ void* pValueC = 0; };

template<class flags>
struct Compound;

template<char...Cs>
struct Compound< flags_tag<Cs...> >:
pValue_t<Cs>...
{};

然后你可以像这样使用它:

using my_type = Compound< decltype( 0x0A_flag ) >;
int main() {
my_type test;
std::cout << test.pValue0 << test.pValueA << '\n';
}

这似乎做你想做的事。

我还会禁用你的 Compound 类型的复制/移动 ctor,并使用 friend 工厂函数将其其他构造函数设为 private .

请注意,此代码可以生成指数级数量的类(2^12 或 4k),这可能会导致二进制膨胀(如果每个类的代码未内联到不存在的情况下)。

[实例]

关于c++ - 使用 C++ 模板编译类成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32639119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com