是否可以将lambda函数作为函数指针传递?如果是这样,我必须做错了,因为我收到编译错误.
请考虑以下示例
using DecisionFn = bool(*)();
class Decide
{
public:
Decide(DecisionFn dec) : _dec{dec} {}
private:
DecisionFn _dec;
};
int main()
{
int x = 5;
Decide greaterThanThree{ [x](){ return x > 3; } };
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译它时,我得到以下编译错误:
In function 'int main()':
17:31: error: the value of 'x' is not usable in a constant expression
16:9: note: 'int x' is not const
17:53: error: no matching function for call to 'Decide::Decide(<brace-enclosed initializer list>)'
17:53: note: candidates are: …Run Code Online (Sandbox Code Playgroud) 是否可以将一个函数及其参数列表传递给另一个函数并稍后从内部调用它?
void testA(int, float, char* ) {}
void testB(int, float, double ) {}
void testC(MyClass, float, double ) {}
template <class T>
void applyA(void(*foo)(void*), std::initializer_list<T> args)
{
foo(/*unpack args somehow*/);
}
template <class T>
void applyB(void(*foo)(void*), std::initializer_list<T> args)
{
MyClass cls;
foo(cls, /*unpack the rest of args*/);
}
int main()
{
applyA(testA, {5, 0.5f, "abc"});
applyA(testB, {5, 0.5f, 1.5});
applyB(testC, {0.5f, 1.5});
}
Run Code Online (Sandbox Code Playgroud)