【问题标题】:Pass a tuple in to a helper class将元组传递给辅助类
【发布时间】:2016-05-16 07:42:50
【问题描述】:

我需要一些帮助来实现我的程序设计。所以我有一个包含我想要的所有内容的元组,从这个调用创建

auto t1 = getMyTuple();

但是我想做一个辅助类,这样我就可以重载

std::cout << my_tuple_helper;

它会打印出每一件事。

我有一个助手类,但我不知道如何让 t1 进入它。它看起来像

template<typename... Args>
class my_tuple_helper
{
  public:
  std::tuple<Args...> my_tup;

  my_tuple_helper(std::tuple<Args... t)
  {
    my_tup = t;
  }

 //or

  my_tuple_helper(Args... args)
  {
    my_tup = std::tuple<Args...>(args...);
  }

};

这些构造函数中的任何一个的问题是如果它是自动类型的对象,我不知道如何在创建对象时传递模板:

auto t1 = getMyTuple();
my_tuple_helper<???> mth(t1);

我编译的东西看起来像这样

template<typename T>
class my_tuple_helper
{
  public:
  T my_tup;

  my_tuple_helper(T t)
  {
    my_tup = t;
  }
};

我可以打电话

auto t1 = getMyTuple();
my_tuple_helper<decltype(t1)> mth(t1);

但我不喜欢 T 可以是任何东西的事实,我宁愿拥有 std::tuple my_tup 而不是 T my_tup(我什至不确定这是否可行)。

有没有人知道如何获得一个存储在 auto 对象中的 std::tuple 到我的辅助类中,以便我可以将它作为 std::tuple 对象(在类中)访问。

提前谢谢你

【问题讨论】:

    标签: c++ templates tuples variadic-templates


    【解决方案1】:

    你可以为此做一个函数

    template<typename... Args>
    my_tuple_helper<Args...>
    make_my_tuple_helper(const std::tuple<Args...>& tup)
    {
        return my_tuple_helper<Args...>(tup);
    }
    

    并使用它

    auto t1 = getMyTuple();
    auto mth = make_my_tuple_helper(t1);
    

    【讨论】:

    • 谢谢我从来没有想过这个!
    【解决方案2】:

    通常的方法是创建一个工厂方法,为您推导出模板参数。所以你会让my_tuple_helper 看起来像这样:

    template<typename... Args>
    class my_tuple_helper
    {
      public:
      std::tuple<Args...> my_tup;
    
      my_tuple_helper(std::tuple<Args...> t)
          : my_tup {std::move(t)}
      { }
    };
    

    然后像这样写一个工厂方法:

    template <typename... Args>
    my_tuple_helper<Args...> 
    make_tuple_helper (const std::tuple<Args...>& t) 
    {
        return { t };   
    }
    

    Live Demo

    如果你想输出你的元组,你可以在一个调用中完成,像这样:

    auto t1 = getMyTuple();
    std::cout << make_tuple_helper(t1);
    

    【讨论】:

    • 非常感谢,您的演示非常有帮助并解决了我的问题 :)
    猜你喜欢
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 2013-01-16
    • 2012-12-28
    • 2016-04-16
    • 1970-01-01
    • 2014-05-18
    相关资源
    最近更新 更多