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

标签 c++ templates c++11 compiler-errors

我有一个类似于此的类:

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/

相关文章:

c++ - Protocol Buffers 的静态链接导致与现有符号的冲突

c++ - 非成员函数 'int find(const T&)' 不能有 cv-qualifier

c++ - 在方法中迭代 vector

c++ - 仅使用 bool 和 char 定义模板类

c++ - std::is_base_of 的 VC2010 实现包含一个错误?

C++ 继承 : Error: candidate expects 1 argument, 0 提供

c++ - C++ 标准是否要求有符号整数只有一个符号位?

c++ - 将多个工具作为单个 bash 脚本运行

c++ - 是否可以为模板提供可变参数列表或根据提供的参数列表自动生成规范

c++ - 使用位掩码生成素数导致程序崩溃