Re: C++ question about perfect forwarding
Am 21.04.2012 03:45, schrieb Jimmy H.:
So let's say my platform (POSIX/Linux) supports a number of
functions that take a varying number of args, but return their error
code in C style, oftentimes as negative numbers signal an error
(which you check errno to discover which error) and non-negative
numbers signal success. I want to write a function which will
automatically throw exceptions when they return errors.
[..]
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?
I assume that you intend that the return type is deduced as well:
#include <utility>
#include <type_traits>
template<typename... Args>
auto posix_neg_error_call(Args&&... args) ->
decltype(func(std::forward<Args>(args)...))
{
using E = decltype(func(std::forward<Args>(args)...));
static_assert(std::is_integral<E>::value, "func() needs to return an
integral type");
E res(func(std::forward<Args>(args)...));
if (res < 0) throw SomeException();
return res;
}
You can also use sfinae to eliminate posix_neg_error_call from the
overload set instead of the static assertion within the function body.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]