我想在函数中实现递归的void表达式。我已经创建了下面的C++片段来说明我的问题。Lambda是我想在Func1中构建的递归的void表达式。但是,当我使用g++编译时,会遇到以下编译器错误:
Lambda_void.cpp: In function ‘void Func1(std::vector<int>&)’:
Lambda_void.cpp:6:10: error: variable or field ‘Lambda’ declared void
void Lambda = [](std::vector<int> &A)
正如我们所知道的,非捕获的lambda函子可以在运行时转换为函数指针,但是编译时如何?也就是说,与下面的代码类似的东西可能吗?请不要建议解决方法,比如将lambda函子作为函数参数传递,我想知道更多的C++11标准是如何禁止的。
template <void(*fptr)()>
void f()
{
// do something
}
int main()
{
auto l([]{});
f<(void(*)())(decltype(l))>();
return 0;
}
gcc-4.8中的强制性错误
c.cpp: In function '
我很好奇这是否可能在另一个函数中创建一个静态函数,然后返回带有参数函数的静态函数。到目前为止,我尝试的内容根本不起作用,当我使用原始函数指针时,代码无法编译。
#include <iostream>
#include <functional>
//both do not work but this one doesn't even compile
/*
void (*func(void (*foo)()))()
{
static void (*copy)();
copy = [&]() { foo(); };
return co
这似乎可以在我尝试过的平台上运行:
#include <iostream>
// extern "C" linkage
extern "C" void foo(void (*fn_ptr)(int));
namespace {
struct bar {
static void f(int);
};
}
int main() {
// Usually works on most platforms, not guaranteed though:
foo(bar::f);
// Probably equally bad
void F(int A[], int n) { // Correct
int arr[3] = {0}; // A[..] in the range of 0-2
for_each(A, A+n, [&arr](const int& num) -> void {
++arr[num];
});
}
void F(int A[], int n) { // Wrong: b/c [arr] should be [&arr]
int arr[3] = {0}; // A[..] in the range of 0-2
// approach 1
template <typename T>
void f1(T t, int a, int b) {
t(a, b);
}
// approach 2
void f2(void(*g)(int, int), int a, int b)
{
g(a, b);
}
void g (int a, int b)
{
// do something
}
int main()
{
f1([](int a, int b)
{
//do something
}, 1,
我想这个问题已经存在了,但我没能找到。
我不明白,为什么需要有一个功能接口来使用lambdas。请考虑以下示例:
public class Test {
public static void main(String...args) {
TestInterface i = () -> System.out.println("Hans");
// i = (String a) -> System.out.println(a);
i.hans();
// i.hans("Hello");
基本上,我的意思是:
void funcForFoo1()
{
// ...
}
void funcForFoo2()
{
// ...
}
void foo()
{
// Other two functions will be used here and here only
}
VS
void foo()
{
auto lambdaForFoo1 = []()
{
// ...
}
auto lambdaForFoo2 = []()
{
// ...
}
// Use the lambdas later on
}
lambda