繁体   English   中英

从 Variadic Function 传递给构造函数的参数声明和初始化 std::tuple

[英]Declaring and Initialising std::tuple from Variadic Function Parameters Passed to Constructor

我正在尝试创建一个 std::tuple 的几个大对象,我可以随后使用,理想情况下访问它们的方法并从 TextureManager 中做其他事情


class TextureManager
{
  public:
  template<typename T , typename... Args>
  TextureManager(T t, Args... args)
                :graphical_objects{std::make_tuple(t, args...)}
  {}

// How to declare graphical_objects ?

  std::tuple< /*what to put here*/  > graphical_objects;
};

int main()
{
  TextureManager tm1(1, 2, 'a');

// This is how I'd like to use TextureManager
  TextureManager text_manager2(my_graphics_obj1, my_graphics_obj2, my_graphics_obj3); 
// Or how ever many parameters...

 return 0;
}

这是 my_graphics_obj1 的玩具示例


class GraphicsObject
{
  virtual void CreateTextures() = 0;
};

class StringTexture: public GraphicsObject
{
  SDL_Texture* CreateTextures (/*params*/)
  {
    // do rendering and what not
    return A_SDL_Texture*;
  }
};

理想情况下,我能够使用元组 graphical_objects 访问 CreateTextures()。 这可能吗?
我用谷歌搜索了我能想到的“成员”、“元组”、“可变参数模板”、“从中提取元素”和“声明使用”的几乎所有可能的单词组合。 我很确定这不是这个问题或这个问题我不会链接到我看过的所有帖子,以节省所有相关时间。 我觉得答案很简单,或者我完全错了,而且涉及更多。

我确实可以访问 C++17,目前我正在使用 clang 进行编译(以获得更好的错误消息),但那是在 C++14 上。 两者/其中一个的解决方案都可以。

我要为自己争取早期的年度最佳面部护理

以下现在在 C++17 中按预期工作。
感谢让我找到解决方案的各种评论。
我还以为我在大约 4 小时前将#include<vector>更改为<tuple> 结果我没有。


#include <iostream>
#include <tuple>

class GraphicsObject
{
  virtual void CreateTextures() = 0;
};

class MandelbrotTexture: public GraphicsObject
{
  float mtf = 78.4;
  void CreateTextures (/*params*/)
  {
    std::cout<<"returning SDL_Texture or GTexure\n";
    return;
  }
};

// template declaration should be here, not where it was...
template<typename T, typename... Args>
class TextureManager
{
  public:

// template<typename T, typename... Args>  this was the wrong place !

  TextureManager(T t, Args... args)
                :graphical_objects(std::make_tuple(t, args...))  // No {} !
  {}

// I'd also forgotten 'T,' and was just trying 'Args...', also wrong.

  std::tuple<T, Args...> graphical_objects;
};

int main(int argc, char const *argv[])
{
  MandelbrotTexture mt;
  TextureManager test(1, 2, 'a');
  TextureManager test2(mt, mt, mt, mt);
  return 0;
}

graphical_objects现在让我可以访问传递给构造函数的对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM