Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using auto in output parameter

Tags:

c++

c++11

auto

Is there a way to use auto keyword in this scenario:

void foo(bar& output){
    output = bar();
} 

int main(){
   //Imaginary code
   auto a;
   foo(a);
}

Of course, it impossible to know what type of a. So, the solution should be to merge them in one sentence in a way or another. Is this available?

like image 899
Humam Helfawi Avatar asked Nov 19 '15 12:11

Humam Helfawi


1 Answers

It looks like you are wanting to default-initialize an object of the type a given function expects as an argument.

You can't do this with auto, but you could write a trait to extract the type a function expects, then use that to declare your variable:

namespace detail {
    //expects the argument number and a function type
    template <std::size_t N, typename Func>
    struct arg_n;

    //does all the work
    template <std::size_t N, typename Ret, typename... Args>
    struct arg_n <N, Ret (Args...)> {
        using type = std::remove_reference_t<
                         std::tuple_element_t<N, std::tuple<Args...>>
                     >;   
    };
}

//helper to make usage neater
template <std::size_t N, typename Func>
using arg_n = typename detail::arg_n<N, Func>::type;

Then you use it like so:

//type of the first argument expected by foo
arg_n<0,decltype(foo)> a{};
foo(a);

Of course, as soon as you overload the function this all fails horribly.

like image 63
TartanLlama Avatar answered Oct 14 '22 10:10

TartanLlama