Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifetime Extension of a initializer_list return

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?

like image 399
Jonathan Mee Avatar asked Jun 06 '16 11:06

Jonathan Mee


1 Answers

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}; };
like image 97
ecatmur Avatar answered Oct 19 '22 16:10

ecatmur