c++ - 如何从另一个类获取std::bitset的大小?

标签 c++ templates

我试图创建一个包含std::bitset的类,另一个类应该将其作为参数并创建一个std::array,以从该类中获取std::bitset的大小。像这样:

template<size_t size>
class Individual{
public:
    std::bitset<size> data;
};

template<typename Ind>
class Process {
public:
    Process() = default;
    std::array<OtherType, Ind::data.size()> individuals;//Size of array must be the size of the bitset!
};
但是,当然这是行不通的(您可以猜测,因为data不是静态的)。如何获取std::bitset的大小并将其放入第二类的std::array中?

最佳答案

问题是在声明Process的过程中,尚不知道IndIndividual,因此尚不能做很多事情。更糟糕的是,data不是静态成员,因此如果没有Ind::data实例,则Process不起作用。幸运的是,根据您的限制,有很多解决方法。
大小作为参数:

template<size_t size>
class Process {
public:
    Process() = default;
    std::array<OtherType, size> individuals;
};
或调整Individual以显示您所需的信息
template<size_t size>
class Individual{
public:
    static const size_t size_ = size; //`static const` is important!
    std::bitset<size> data;
};

template<typename Ind>
class Process {
public:
    Process() = default;
    std::array<OtherType, Ind::size_> individuals;
};
或作为部分特化:
template<typename Ind>
class Process {
   static_assert(sizeof(T)==0, "param must be of type Individual")
   //or whatever you want for non-Individual parameters
};
template<size_t size>
class Process<Individual<size>> {
public:
    Process() = default;
    std::array<OtherType, size> individuals;
};
或使用部分专门的帮助程序类:
template<class T>
struct size_helper {
   static_assert(sizeof(T)==0, "must specialize size_helper");
};

template<size_t size>
class Individual{
public:
    std::bitset<size> data;
};

template<size_t size_>
struct size_helper<Individual<size_>> {
   static const size_t size = size_;
};

template<typename Ind>
class Process {
public:
    static const size_t size = size_helper<Ind>::size;
    Process() = default;
    std::array<OtherType, Ind::size_> individuals;
};

关于c++ - 如何从另一个类获取std::bitset的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63139353/

相关文章:

c++如何初始化部分模板特化的静态变量

templates - 使用带有 knockout 的外部模板的最佳方法

c++ - Linux 中的嵌套 vector

c++ - 未识别的 C++ 函数引用

c++ - Visual Studio 无法识别模板类中的结构

c++ - '&' token 之前的C++预期构造函数,析构函数或类型转换

c++ - 为什么我在这段代码中出现编译错误?

c++ - 隐藏在类默认模板参数后面的方法中的默认模板参数

C++ 函数采用整数,但示例显示文本?

c++ - '< >' 在 C++ 中意味着什么?