C ++ 11 variadic args with default function argument value

I have a wrapper that calls a template function N times:

template <std::uint16_t N, typename F, typename ... Args> inline typename std::result_of<F && (Args &&...)>::type retry_n(F && f, Args&& ... ax) { for (auto i = 0; i < N; ++i) { try { return std::forward<F>(f)(std::forward<Args>(ax)...); } catch (const some_except &e){ /*ignore exception for a while*/ } } throw;//re-raise } 

Everything works fine until I pass a function with a default argument:

 int f(int a, int b, int c = 5); .... retry_n<10>(f, 1, 2); // error C2198: 'bla-bla' : too few arguments for call 

How to allow the use of a default argument without an explicit specification?

+5
source share
1 answer

The default parameter is not part of the function signature and is not involved in template type output. Therefore, whenever you pass from f to retry_n<> , the type f is displayed as int(int, int, int) , so the local f refers to this last type, and the default parameters are outside the process. Your only solution is to use the function that you want to test directly without inferring its type, as in the comment of @Johannes Schaub-litb, or if your compiler does not support common lambdas (C ++ 14), wrap it in a functor with a variational pattern operator()

 struct functor { template<typename... T> int operator()(T&&... params) { return f(std::forward<T>(params)...); } }; 

and use it as

 retry_n<10>(functor{}, 1, 2); 
+2
source

Source: https://habr.com/ru/post/1235785/


All Articles