我试图创建一个具有std::bitsetin的类,另一个类应该将它作为参数并创建一个从类中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!
};
Run Code Online (Sandbox Code Playgroud)
但是当然这不起作用(您可以猜到,因为data不是静态的)。如何从第二个类中获取 the 的大小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;
};
Run Code Online (Sandbox Code Playgroud)
或调整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;
};
Run Code Online (Sandbox Code Playgroud)
或者作为部分专业化:
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;
};
Run Code Online (Sandbox Code Playgroud)
或者使用部分专门化的帮助类:
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;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37 次 |
| 最近记录: |