Re: C++ question about perfect forwarding
On 21 Apr., 03:45, "Jimmy H." wrote:
[...]
I can do it if I already know the number of arguments:
template<typename A, typename B, typename C, typename D, typename E>
E posix_neg_error_call3(A func, B arg1, C arg2, D arg3) { // These C
functions always take args by value
E res(func(arg1, arg2, arg3));
if (res < 0) throw SomeException();
return res;
}
But how do I make this work for any number of arguments using
variadic templates?
Like this:
template<class Func, class...Args>
typename std::result_of<Func(Args...)>::type
invoke_and_conditionally_throw(Func func, Args&&...args)
{
typedef typename std::result_of<Func(Args...)>::type returntype;
returntype res = func(std::forward<Args>(args)...);
if (res<0) throw SomeException();
return std::forward<returntype>(res);
}
Note that you don't have to introduce another template parameter for
the return type. Also, the code above does support functors that
return references. Of course, this is not possible in C and you might
as well write
auto res = ...;
:::
return res;
instead. :-)
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]