You cannot have such a template function pointer, but remember that a lambda is merely syntactical sugar, you can just write the class yourself.
class fp {
template<class AT, class BT>
void operator()(AT&& a, BT&& b) {
std::cout << a << "--" << b << std::endl;
};
};
class class_with_functionoid_member {
fp fn_;
};
And the more generic version would be that you can have the lambda as a member. You have to take the lambda type as a class parameter.
template<class fnT>
class class_with_lambda_member {
fnT fn_;
public:
class_with_lambda_member(fnT fn) : fn_(std::move(fn)) {}
};
The gist is that a function pointer is a type of runtime type erasure, and template member functions require compile time lazy instantiation, and C++ has no way to mix these two concepts. All the workarounds that come to mind revolve around explicitly listing out every possible combination of T1 and T2` in the "interface", which doesn't mix with a function pointer, but can work with a function pointer looking object.
struct erasable_functions {
virtual ~erasable_functions(){}
virtual void operator()(int, int)=0;
virtual void operator()(int, char)=0;
virtual void operator()(char, int)=0;
virtual void operator()(char, char)=0;
};
template<class lambdaT>
struct erased_functions : erasable_functions {
lambdaT lambda_;
erased_functions(lambdaT lambda) : lambda_(std::move(lambda)){}
virtual void operator()(int a, int b) {lambda_(a, b);
virtual void operator()(int a, char b) {lambda_(a, b);
virtual void operator()(char a, int b) {lambda_(a, b);
virtual void operator()(char a, char b) {lambda_(a, b);
};
template<class lambdaT>
erased_functions<lambdaT> erase_functions(lambdaT lambda)
{return {std::move(lambda)};}
struct class_with_functionoid_member {
erasable_functions* functions_;
class_with_functionoid_member(erasable_functions* functions) : functions_(functions){}
void operator()(int a, int b) {(*functions_)(a, b);
void operator()(int a, char b) {(*functions_)(a, b);
void operator()(char a, int b) {(*functions_)(a, b);
void operator()(char a, char b) {(*functions_)(a, b);
};
int main() {
auto lambda = erase_functions([](auto a, auto b) {
std::cout << a << "--" << b << std::endl;
};
class_with_functionoid_member c(&lambda);
}