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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With