c++11 - 将参数包存储为元组引用
问题描述
我正在尝试存储可变参数模板的左值引用的参数包以供以后使用。
我现在有以下工作。
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);
}
但是,我想将参数包存储为引用,以便以后可以访问同一个对象。我不确定我该怎么做。任何帮助,将不胜感激。
解决方案
我能想象的最好的就是使用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...)}
{ }
};
我希望没有必要记住你对于基于引用元组的解决方案来说,悬空引用是多么危险。
推荐阅读
- java - 服务中的@Autowired 类无法解析为控制器类中的类型
- android - 嘿,我正在创建一个聊天应用程序,但检索消息时出现问题
- prometheus - 将字符串附加到 Prometheus 目标参数
- python - 称为列表元素时无法识别字符串
- node.js - Node.js Express 将大型视频流式传输到客户端
- delphi - 从 Delphi 7 转换到 Delphi 10.3 时参数列表不兼容
- sql - 如何在 Oracle PL/SQL 中实现 AFTER INSERT 触发器?
- numpy - “错误”的 TF IDF 分数
- sql - 插入具有不同(控制重复)一列
- vue.js - 如何从组件模板内的 Vuex getter 获取更新的值?