如何拥有指向通用lambda的函数指针? [英] How to have a function pointer to a generic lambda?
问题描述
正如标题所述,如何在代码中表达以下意图?作为函数指针的要求采用任何类型的参数.由于 std :: string
.Variadic无法正常工作.
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
.
请注意,由于 fp
是类成员变量,因此我不能直接使用 auto fp =< the lambda>
.
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');
}
当然,手动对lambda进行减半运算并获取其实例会更实用:
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;
遗憾的是,我们不能简单地给lambda一个名称并让编译器弄清楚.
为合适的语法集思广益:
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 = []...;
这篇关于如何拥有指向通用lambda的函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!