As the title says, how can I have the following intent expressed in code ? The requirements being the function pointer takes any type of arguments. Variadic doesn't work because of std::string
.
Note that I cannot directly use auto fp = <the lambda>
because fp
is a class member variable.
#include <iostream>
template<typename T1, typename T2>
void(*fp)(T1 t1, T2 t2) = [](auto a, auto b){
std::cout << a << "--"
<< b << std::endl;
};
int main(){
fp(1, 2);
fp('a', 'b');
}
A variable template is perfectly fine.
Even the way you initialize them is fine.
Just be aware it is a template for variables, not a variable storing a template (which cannot exist).
Thus when finally using it, things fall apart:
How should the compiler know which of the myriad potential instances you mean?
Simple, you have to actually tell it:
int main(){
fp<int, int>(1, 2);
fp<char, char>('a', 'b');
}
Of course, manually desugaring the lambda and getting an instance of it would be more practical:
struct {
template <class T1, class T2>
void operator()(T1 a, T2 b) const {
std::cout << a << "--" << b << std::endl;
};
} fp;
A shame we cannot simply give a lambda a name and let the compiler figure it out.
Brainstorming candidates for appropriate syntax:
struct A = []...;
struct B : []... {
};
using C = []...;