Hi I'm trying to sort out an issue with the following code:
template<typename... Args>
using Func = void (*)(Args... args);
template<typename... Args>
void do_test(Func<Args&...> f, Args&... args) {
for (int i = 0; i != 100; i++)
f(args...);
}
int main(){
int x = 0;
do_test(Func<int&>([](int &y) { y++; }), x); // OK
// Error - mismatched types 'void (*)(Args& ...)' and 'main()::<lambda(int&)>'
do_test([](int &y) { y++; }, x);
return x;
}
Can anyone explain why it is necessary to wrap the lambda in Func<int&>( )
? Is there a way to avoid it? - because if the argument list is non-trivial it becomes quite tedious having to list out the argument types twice.
The goal here is to make a visitor pattern that the compiler can optimize away. I'm using it for an image processing algorithm where I want to reuse the code of the outer loops, with various bits of inner code. The Args
are being used as something similar to a lambda capture, except using traditional function pointers so that the compiler can optimize them away - which it seems not to be able to do with std::function<>