initializer_list返回的生命周期扩展 [英] Lifetime Extension of a initializer_list return

查看:78
本文介绍了initializer_list返回的生命周期扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个返回类型为auto的lambda,并且在initializer_list的数组支持方面存在问题,在这里被破坏:

So I have a lambda who's return type is auto and I'm having issues with the array backing for an initializer_list being destroyed here:

const auto foo = [](const auto& a, const auto& b, const auto& c) { return {a, b, c}; };

我将像这样使用lambda:

I will be using the lambda like this:

auto bar = foo(1, 2, 3);

for(const auto& i : bar) cout << i << endl;

我正在从事的工作是其编码标准的一部分,即所有的lambda都是单个语句(随意表达您的愤慨.)我想我可以通过以下方法解决此问题:

A job that I'm working has as part of their coding standard that all lambdas are single statements (feel free to express your outrage.) I think that I can get around this by:

  1. foo一个返回类型vector int,但这弄乱了它的通用性:const auto foo = [](const auto& a, const auto& b, const auto& c) -> vector<int> { return {a, b, c}; }
  2. 只需编写一个构造函数即可构造vector<T>并返回它:template <typename T> vector<T> foo(const T& a, const T& b, const T& c){ return {a, b, c}; }
  1. Giving foo a return type of vector int, but that messes up how nicely generic it is: const auto foo = [](const auto& a, const auto& b, const auto& c) -> vector<int> { return {a, b, c}; }
  2. Just writing a templatized function which constructs a vector<T> and returns it: template <typename T> vector<T> foo(const T& a, const T& b, const T& c){ return {a, b, c}; }

是否可以将这些变量强制放入一个容器中,谁的支持不会在一行中被全部破坏,以便我可以将lambda保留为auto返回类型?

Is it possible to coerce these variables into a container, who's backing won't be destroyed all in one line so that I can keep the lambda with an auto return type?

推荐答案

库基本原理TS v2具有

The library fundamentals TS v2 has std::experimental::make_array, which would certainly satisfy your requirements:

#include <experimental/array>
const auto foo = [](const auto& a, const auto& b, const auto& c) {
    return std::experimental::make_array(a, b, c); };

更一般地,针对构造函数的模板参数推导允许您编写:

More generally, template argument deduction for constructors would allow you to write:

const auto foo = [](const auto& a, const auto& b, const auto& c) {
    return std::vector{a, b, c}; };
                      ^-- no template parameter required

今天,您可以使用 common_type

Today, you could emulate this using common_type:

const auto foo = [](const auto& a, const auto& b, const auto& c) {
    return std::vector<std::common_type_t<decltype(a), decltype(b), decltype(c)>>{a, b, c}; };

这篇关于initializer_list返回的生命周期扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆