首页 > 解决方案 > 将参数包存储为元组引用

问题描述

我正在尝试存储可变参数模板的左值引用的参数包以供以后使用。

我现在有以下工作。

template <typename... Ts>
class Foo {
private:
        std::tuple<Ts...> m_args;
public:
       template<typename... Args>
       Foo(Args&&... args) : m_args(std::make_tuple(std::forward<Args>(args)...))
       {
       }
 };

 int main() {
     int x = 10;
     int y = 20;
     Foo<int, int> foo(x, y);
 }

但是,我想将参数包存储为引用,以便以后可以访问同一个对象。我不确定我该怎么做。任何帮助,将不胜感激。

标签: c++11tuplesvariadic-templatesvariadic-functionsperfect-forwarding

解决方案


我能想象的最好的就是使用std::forward_as_tuple.

不幸的是,我没有看到一种将它与完美转发一起使用的方法:如果你想在一个类的元组中注册值,你必须一次性决定元组的类型。

我能想象的最好的是一个 const 引用的元组;如下

template <typename ... Ts>
class Foo
 {
   private:
      std::tuple<Ts const & ...> m_args;

   public:
      Foo (Ts const & ... as) : m_args{std::forward_as_tuple(as...)}
       { }
 };

我希望没有必要记住你对于基于引用元组的解决方案来说,悬空引用是多么危险。


推荐阅读