模板双缓冲区类

发布于 2025-02-10 03:44:53 字数 463 浏览 0 评论 0原文

我有一个包装相同类型的2个缓冲区的课程,我需要一些用于这些缓冲区的固定器和获取器,我不想重复代码。我想用模板来实现这一目标,但我不知道该怎么做。我放了一些错误的代码只是为了理解这个想法:

class DualBuffer{
 public:
  template <int idx>
  inline float<idx>* arr() {  
    // ...
  }
 private:
  float* arr0;
  float* arr1;
};

int main(){
  DualBuffer db;
  float* arr0 = db.arr<0>(); // returns a ptr to arr0
  float* arr1 = db.arr<1>(); // returns a ptr to arr1
}

这是可以实现的吗?有人可以用一些实施细节指向正确的方向吗?

I've a class that wraps 2 buffers of the same type, I need some setters and getters for these buffers and I don't want to duplicate code. I'd like to achieve this with templates but I don't know how to do it. I put some wrong code just to get the idea:

class DualBuffer{
 public:
  template <int idx>
  inline float<idx>* arr() {  
    // ...
  }
 private:
  float* arr0;
  float* arr1;
};

int main(){
  DualBuffer db;
  float* arr0 = db.arr<0>(); // returns a ptr to arr0
  float* arr1 = db.arr<1>(); // returns a ptr to arr1
}

Is this achievable? Can someone point me in the right direction with some implementation details?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

临风闻羌笛 2025-02-17 03:44:53

最简单的方法是使用std ::数组。但是,对于此特定示例,您还可以使用定义的方法arr,而无需它作为函数模板,如下所示:

class DualBuffer{
 public:
  //ordinary method instead of function template
  float* arr(std::size_t index) {  
    switch (index) {
      case 0: return arr0;
      case 1: return arr1;
      
      default: throw "not valid index";
    }
  
  }
 private:
  float* arr0 = nullptr;
  float* arr1 = nullptr;
};

int main(){
  DualBuffer db;
  float* arr0 = db.arr(0); // returns arr0
  float* arr1 = db.arr(1); // returns arr1
}

The simplest way would be to use std::array. But for this particular example you can also use the method arr that you defined without needing it to be a function template as shown below:

class DualBuffer{
 public:
  //ordinary method instead of function template
  float* arr(std::size_t index) {  
    switch (index) {
      case 0: return arr0;
      case 1: return arr1;
      
      default: throw "not valid index";
    }
  
  }
 private:
  float* arr0 = nullptr;
  float* arr1 = nullptr;
};

int main(){
  DualBuffer db;
  float* arr0 = db.arr(0); // returns arr0
  float* arr1 = db.arr(1); // returns arr1
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文