Lifetime Extension of a initializer_list return

给你一囗甜甜゛ 提交于 2019-12-19 07:43:06

问题


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}; };

I will be using the lambda like this:

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

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

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. 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}; }

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?


回答1:


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

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}; };


来源:https://stackoverflow.com/questions/37656076/lifetime-extension-of-a-initializer-list-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!