我试图创建一个包含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
的过程中,尚不知道Ind
是Individual
,因此尚不能做很多事情。更糟糕的是,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/