我开始使用C++ 11 lambdas开发应用程序,并且需要将某些类型转换为函数指针.这在GCC 4.6.0中完美运行:
void (* test)() = []()
{
puts("Test!");
};
test();
Run Code Online (Sandbox Code Playgroud)
我的问题是当我需要在lambda中使用函数或方法局部变量时:
const char * text = "test!";
void (* test)() = [&]()
{
puts(text);
};
test();
Run Code Online (Sandbox Code Playgroud)
G ++ 4.6.0给出了强制转换错误代码:
main.cpp: In function 'void init(int)':
main.cpp:10:2: error: cannot convert 'main(int argc, char ** argv)::<lambda()>' to 'void (*)()' in initialization
Run Code Online (Sandbox Code Playgroud)
如果使用auto,它可以正常工作:
const char * text = "Test!";
auto test = [&]()
{
puts(text);
};
test();
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何用[&]为lambda创建一个类型?在我的情况下,我不能使用STL std :: function(因为我的程序不使用C++ RTTI和EXCEPTIONS运行时),并且它有一个简单的函数实现来解决这个问题?
我正在尝试使用lambda,当测试以下时,编译说'hi'.
auto lmda = [](std::ostream& os) -> std::ostream& { os << "hi"; return os; };
std::cout << lmda;
Run Code Online (Sandbox Code Playgroud)
但是在添加捕获时,它不会编译.例:
std::vector<int> v(5, 3);
auto lmda = [&v](std::ostream& os) -> std::ostream& { os << v.size(); return os; };
std::cout << lmda;
Run Code Online (Sandbox Code Playgroud)
构建错误是:
In function 'int main()':
10:18: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
In file included from /usr/include/c++/4.9/iostream:39:0,
from 2:
/usr/include/c++/4.9/ostream:602:5: note: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; …Run Code Online (Sandbox Code Playgroud) 我正在寻找一种在C++中装饰函数或lambdas的方法.目标是在函数调用之前和之后执行某些操作.正如我所见,最接近使用的是std :: function,但它需要具有其参数的类型.
class FunctionDecorator
{
public:
FunctionDecorator( std::function func )
: m_func( func )
void operator()()
{
// do some stuff prior to function call
m_func();
// do stuff after function call
}
private:
std::function m_func;
};
Run Code Online (Sandbox Code Playgroud)
如果模板类型可以在std :: function中使用它会很好,当我将指针传递给函数或std :: bind的结果时,它可以以某种方式推导出它.在C++中这样的事情是否可行.
我正在尝试使用 lambda 函数来快速测试事物,但我正与它撞墙。我不知道为什么事情没有像(我觉得)应该的那样工作。
这正如我所期望的那样工作:
double(*example)(double) = [](double S)->double {return std::max(1-100/S, 0.0) * LogNormal(S, 100, 0.25); };
NewtonCotes(lowerBound, upperBound, example, intervals, order)
Run Code Online (Sandbox Code Playgroud)
然而,这不会:
double(*example)(double) = [K](double S)->double {return std::max(1 - K / S, 0.0) * LogNormal(S, 100, 0.25); };
Run Code Online (Sandbox Code Playgroud)
给出错误:
错误:不存在从“lambda []double(double S)->double”到“double(*)(double)”的合适转换函数。
我不明白为什么在捕获列表中添加一些东西会改变这里发生的事情。不过,我对 C++ 中的 lambdas 还很陌生,所以可能在某处犯了一个愚蠢的错误......
我需要做什么才能让它发挥作用?我已经看到一些人注意到智能感知中存在一个错误,并且像这样的事情应该可以工作,尽管这是一个略有不同的问题(至少我认为它们不完全匹配)。我也在使用 VS2013,而不是 2011 年提到的那个 bug。
下面的代码很高兴被GCC和Clang接受,-std=c++14但导致Visual Studio 2013出现编译错误.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
auto increasing = [](int lhs, int rhs){return lhs < rhs;};
auto decreasing = [](int lhs, int rhs){return lhs > rhs;};
std::vector<int> v(0, 10);
bool increase = true;
std::sort(v.begin(), v.end(), increase ? increasing : decreasing);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误是:
main.cpp(11): error C2446: ':': no conversion from 'main::<lambda_0228ee097b83254cfd8aa5f4015a245b>' to 'main::<lambda_cb3b816d067baa9d4462132ee332363c>'
main.cpp(11): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot …
我有一个冒泡排序函数,它接受一个数组,一个比较函数和一个布尔值,指示它是否应该对数组进行倒置排序.它是一个支持任何数据类型的模板函数,并将自动推导出数组大小.
指定比较函数时,如果我传递函数指针,编译器会自动推导出数组的数据类型,这很好.但是,如果我改为传递lambda,它将不会自动推断.我必须明确指定数据类型,或static_cast将lambda指定为fnCompare_t<double>.
这背后的原因是什么?因为根据这篇文章,只要lambda不捕获,它就可以像普通的函数指针一样使用,但似乎并非总是如此?在这种情况下怎么会有所不同?
#include <iostream>
using namespace std;
template <typename T>
using fnCompare_t = int(*)(T const &, T const &);
template <typename T, size_t count>
inline void BubbleSort(
T(&array)[count],
fnCompare_t<T> fnCompare,
bool reverse)
{
cout << "TODO: Implement BubbleSort" << endl;
}
double doubleArray[] = {
22.3, 11.2, 33.21, 44.2, 91.2, 15.2, 77.1, 8.2
};
int CompareDouble(double const & a, double const & b)
{
return a > b ? 1 : a == …Run Code Online (Sandbox Code Playgroud) 我有一个虚函数,它根据派生类返回不同的 lambda:
class Base
{
public:
virtual std::function<float()> foo(void) = 0;
};
class Derived : public Base
{
public:
std::function<float()> foo(void) {
return [] __device__ (void) {
return 1.0f;
};
}
};
Run Code Online (Sandbox Code Playgroud)
然后我想将此 lambda 传递给 CUDA 内核并从设备调用它。换句话说,我想这样做:
template<typename Func>
__global__ void kernel(Func f) {
f();
}
int main(int argc, char** argv)
{
Base* obj = new Derived;
kernel<<<1, 1>>>(obj->foo());
cudaDeviceSynchronize();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面给出了这样的错误:calling a __host__ function("std::function<float ()> ::operator ()") from a __global__ function("kernel< ::std::function<float ()> > ") is …
我想将我的类方法作为参数传递给接受函数指针和void*. 下面是一个例子:
#include <functional>
typedef void(*pfnc) (void*);
struct Foo
{
static void static_foo(void*)
{
}
void foo(void*)
{
}
void listner(pfnc f, void* p)
{
f(p);
}
void test()
{
listner(static_foo); // works with static method
auto f = [](void*) {};
listner(f); // works with lambda
std::function<void(void*)> stdf = std::bind(&Foo::foo, this, std::placeholders::_1);
listner(stdf); // does not compile with not static method
}
};
Run Code Online (Sandbox Code Playgroud)
不幸的是我的解决方案无法编译。我必须改变什么?
我最近在使用 C++ 时遇到了一些问题,基本上是这样的:
在函数内部(比如 int main),我声明了一个变量 Y = 5,并且我有这个 lambda 函数,它接收一个值并将 Y 相加;
我的问题是:我需要将此 lambda 函数传递给一个已经存在的函数,以便可以在另一个函数内部调用它。
我尝试了几件事,但都没有按我的预期工作(有些甚至没有工作):
double receives( double (*f)(double) )
{
return f(5);
}
int main()
{
int y = 5;
auto fun = [](double x) {
return x + y;
};
cout << receives(&fun);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
另一个问题是我无法更改我的接收函数签名,由于代码的其余部分,参数必须是 double (*f)(double)。我还需要 lambda 函数来传递 y 值,而不使用其他参数。
任何人都可以帮助我吗?
......为前一个道歉
在C++中我们如何执行以下操作
// fundamental language construct
type name = value ;
// for example
int x = y;
Run Code Online (Sandbox Code Playgroud)
用函数指针?
typedef (char)(*FP)(unsigned);
// AFAIK not possible in C++
FP x = y ;
Run Code Online (Sandbox Code Playgroud)
我可以用lambdas:
FP x = []( unsigned k) -> char { return char(k); }
Run Code Online (Sandbox Code Playgroud)
但我不知道如何在没有lambda的情况下做到这一点.有任何想法吗?
c++ ×10
c++11 ×5
lambda ×5
function ×2
bind ×1
c++14 ×1
cuda ×1
parameters ×1
templates ×1
visual-c++ ×1