1

Currently using g++11.3.0, C++20.

I'm trying to compile the code below, where the function foo takes an arbitrary number of template arguments and returns a tuple that contains a value for each template argument. The code compiles and runs for me when I use the statements foo<int>() and foo<float>(), but runs into an error when I use the statement foo<int, float>():

error: no viable conversion from returned value of type 'tuple<typename __unwrap_ref_decay<float>::type, (no argument)>' to function return type 'tuple<int, float>'

However, if I change the return type from std::tuple<Args...> to auto, it compiles and runs for all three statements. Is return type deduction the only way to go or is there a way to avoid using the auto keyword?

template <typename ...Args>
std::tuple<Args...> foo()
{
    return std::make_tuple(([] ()
    {
        // Do some stuff....
        // Return value....

        return Args();
    }(), ...));
}
1
  • 3
    You are using the comma operator, so the function always returns a tuple of one element. it should be return std::make_tuple([] () { return Args(); }()...);
    – 康桓瑋
    Feb 5 at 13:26

1 Answer 1

2

You use the syntax for folding expression using comma operator, instead you need:

template <typename ...Args>
std::tuple<Args...> foo()
{
    return std::make_tuple([] ()
    {
        // Do some stuff....
        // Return value....

        return Args();
    }()...);
}
2
  • Does the current function return a tuple of references already? Or just a tuple of l-values? If I wanted to return a tuple of l-value references, what would I have to change? I tried changing the return type to std::tuple<Args&...> and using std::tie, but it gave me the error no matching function for call to 'tie'.
    – incur8203
    Feb 6 at 0:13
  • As written, foo<int, float> returns std::tuple<int, float> (you would need foo<int&, float&>, but). std::make_tuple is the wrong tool (unless you use std::reference_wrapper<X>), the lambda should also return a reference (and reference are not default constructible)... Several changes, hard to write expected code with those broad information.
    – Jarod42
    Feb 6 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.