[英]How to code a union using a struct as template, while having that union as an element
我希望能够做到这一点:
p = p->pLR.array[value>insertValue];
除了旧的分支
if(value>insertValue) p = p->right;
else p = p->left;
1b。 这并不完全是为了避免代价高昂的分支错误预测,而仅仅是为了能够学习实现类似的东西。
这是我未编译的代码:
template <class dataType, class BinaryNode<dataType> >
union BinaryNodePointerPair {
struct {
BinaryNode<dataType> *left;
BinaryNode<dataType> *right;
};
BinaryNode<dataType> *array[2];
};
template <class dataType>
struct BinaryNode {
dataType value;
BinaryNodePointerPair<dataType,BinaryNode<dataType> > pLR;
};
[Error] 'BinaryNode' is not a template
重构自:
template <class dataType>
struct BinaryNode {
dataType value;
BinaryNode *left;
BinaryNode *right;
};
3a。 根据“ X不是模板”错误 ,模板应为
template <class dataType, class <dataType>BinaryNode >
[Error] expected identifier before '<' token
[Error] expected '>' before '<' token
[Error] type/value mismatch at argument 2 in template parameter list for 'template<class dataType, int <anonymous> > union BinaryNodePointerPair'
3b。 所以我将其更改为
template <class dataType, class BinaryNode<dataType> >
但这给出了错误以及原始错误。
[Error] 'BinaryNode' is not a class template
[Error] 'class BinaryNode' is not a valid type for a template non-type parameter
[Error] 'BinaryNode' is not a template
3c。 所以我再次将其更改为
template <class dataType, class BinaryNode<dataType> >
但这会带来更多错误
[Error] 'BinaryNode' is not a class template
[Error] 'class BinaryNode' is not a valid type for a template non-type parameter
[Error] 'BinaryNode' is not a template
[Error] 'BinaryNode' is not a template type
3d。 现在,这非常接近CRTP(无需告诉我这不是真正的CRTP,但这很奇怪)
template <class dataType>
union BinaryNodePointerPair {
struct {
BinaryNode<dataType> *left;
BinaryNode<dataType> *right;
};
BinaryNode<dataType> *array[2];
};
template <class dataType, BinaryNodePointerPair<dataType> >
struct BinaryNode {
dataType value;
BinaryNodePointerPair<dataType> pLR;
};
[Error] 'BinaryNode' is not a template
只有1个错误! 哇! 这一定是赢家!
3e。 现在,我真的真的将其强制设置为CRTP模式了,甚至更糟。
template <class dataType, class BinaryNode<dataType> >
union BinaryNodePointerPair {
struct {
BinaryNode<dataType> *left;
BinaryNode<dataType> *right;
};
BinaryNode<dataType> *array[2];
};
template <class dataType>
struct BinaryNode {
dataType value;
BinaryNodePointerPair<dataType, BinaryNode<dataType>> pLR;
};
[Error] 'BinaryNode' is not a class template
[Error] 'class BinaryNode' is not a valid type for a template non-type parameter
[Error] 'BinaryNode' is not a template
不必是CRTP。 有办法吗?
如何编写带有指向具有该联合元素的结构的指针的联合?
我没有真正的问题,但是您是否忘记了BinaryNode
的前向声明?
template <class dataType>
struct BinaryNode;
template <class dataType>
union BinaryNodePointerPair
{
struct
{
BinaryNode<dataType> *left;
BinaryNode<dataType> *right;
};
BinaryNode<dataType> *array[2];
};
template <class dataType>
struct BinaryNode
{
dataType value;
BinaryNodePointerPair<dataType> pLR;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.