加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – “追溯联盟” – 可以吗?

发布时间:2020-12-16 10:45:59 所属栏目:百科 来源:网络整理
导读:我有两个类:一个模板类,一个继承它的常规类: template int N class Vector{ float data[N]; //etc. (math,mostly)};class Vector3 : public Vector3{ //Vector3-specific stuff,like the cross product}; 现在,我想在子类中使用x / y / z成员变量(完整成员
我有两个类:一个模板类,一个继承它的常规类:

template <int N> class Vector
{
    float data[N];
    //etc. (math,mostly)
};

class Vector3 : public Vector<3>
{
    //Vector3-specific stuff,like the cross product
};

现在,我想在子类中使用x / y / z成员变量(完整成员,而不仅仅是getter – 我希望能够设置它们).但是为了确保所有(继承的)数学运算出来,x必须引用与data [0],y到data [1]等相同的内存.基本上,我想要一个联合,但我不能在基类中声明一个,因为我不知道该点向量中的浮点数.

那么 – 这可以吗?是否有某种预处理器/ typedef /模板魔法可以实现我正在寻找的东西?

PS:我正在使用g 4.6.0和-std = c 0x,如果这有帮助的话.

编辑:虽然引用会给出我正在寻找的语法,但理想的解决方案不会使类更大(并且引用做了很多!Vector< 3>是12字节.带引用的Vector3是40!) .

解决方法

怎么样:

class Vector3 : public Vector<3>
{
public:
  // initialize the references...
  Vector3() : x(data[0]),y(data[1]),z(data[2]){}
private:
  float& x;
  float& y;
  float& z;
};

当然,如果你想让它们占据同一个空间,那就是另一个故事……

使用一点模板魔法,您可以执行以下操作…

#include <iostream>

template <int N,typename UnionType = void*> struct Vector
{
    union
    {
      float data[N];
      UnionType field;
    };

    void set(int i,float f)
    {
      data[i] = f;
    }

    // in here,now work with data
    void print()
    {
      for(int i = 0; i < N; ++i)
        std::cout << i << ":" << data[i] << std::endl;
    }
};

// Define a structure of three floats
struct Float3
{
  float x;
  float y;
  float z;
};

struct Vector3 : public Vector<3,Float3>
{
};

int main(void)
{
  Vector<2> v1;
  v1.set(0,0.1);
  v1.set(1,0.2);
  v1.print();

  Vector3 v2;
  v2.field.x = 0.2;
  v2.field.y = 0.3;
  v2.field.z = 0.4;
  v2.print();

}

编辑:读完评论后,我意识到我之前发布的内容确实没有什么不同,所以稍微调整一下上一次迭代就可以直接访问该字段(这就是我猜你会想到的) – 我猜这个区别而Rob的解决方案是你不需要所有专业知识来反复实现所有逻辑……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读