问题描述
在本主题的继续中,我想询问以下内容。假设我们有几个类,两个成员是动态数组。现在假设有一系列这些类的对象,它们被打包在异构容器中。在该序列中,阵列中的一个是输出向量,另一个阵列成员是输入向量,其是指向来自前一对象的适当输出阵列的指针。这个序列被实现为可变参数模板类:
In continuation of this topic Variadic template heterogeneous container, I would like to ask the following. Assume, that we have several classes with two members that is dynamic arrays. Now suppose that there is a sequence of objects of these classes, which is packed in heterogeneous container. In this sequence one of arrays-mebers is "output" vector and another array-member is "input" vector, which is pointer to appropriate output array from preceding object. This sequence is implemented as variadic template class:
//Classes, objects which are members of the sequence
template<int NumberElements>
struct A
{
A() : output(new float[NumberElements]){}//allocate output
~A(){delete[] output;}
float *input;//input vector - pointer to output vector from preceding object of sequence
float *output;// output vector (size - NumberElements) of current member of sequence
};
template<int NumberElements>
struct B
{
B() : output(new float[NumberElements]){}//allocate output
~B(){delete[] output;}
float *input;
float *output;
};
template<int NumberElements>
struct C
{
C() : output(new float[NumberElements]){}//allocate output
~C(){delete[] output;}
float *input;
float *output;
};
//Container
template<typename...Arg>
struct HeterogenousContainer
{
HeterogenousContainer();//Do something to setup the sequence
std::tuple<Arg...> elements;
};
如何正确分配内存(通过 new / malloc )输出向量,并设置输入指向先前输出向量的指针?例如,我写下一个代码:
How can I properly allocate memory (via new/malloc) for output vectors, and set up input pointers to preceding output vectors? For example, I write next code:
HeterogenousContainer<A<5>, B<7>, C<9>> sequence;
我希望来自序列第一个成员的输入
I want that input from first member of sequence to be nullptr, input from second - points to output from first, etc. How to implement it correctly?
受启发,(没有双关语),我想出了这个:
Inspired by Useless' answer (no pun intended), I came up with this:
template<typename...Arg>
struct HeterogenousContainer
{
std::tuple<Arg...> elements;
void init(std::integral_constant<std::size_t, 0>)
{
std::get<0>(elements).input = nullptr;
}
template < std::size_t index = sizeof...(Arg)-1 >
void init(std::integral_constant<std::size_t, index> = {})
{
std::get<index>(elements).input = std::get<index-1>(elements).output;
init(std::integral_constant<std::size_t, index-1>{});
}
HeterogenousContainer()
: elements{}
{
init();
}
};
这篇关于异构序列生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!