是否可以将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) 在C++中实现回调函数时,我是否还应该使用C风格的函数指针:
void (*callbackFunc)(int);
Run Code Online (Sandbox Code Playgroud)
或者我应该使用std :: function:
std::function< void(int) > callbackFunc;
Run Code Online (Sandbox Code Playgroud) 我正在讨论在C++中实现策略模式的最佳方法.到目前为止,我一直使用标准方式,其中上下文具有指向基本策略类的指针,如下所示:
class AbstractStrategy{
public:
virtual void exec() = 0;
}
class ConcreteStrategyA{
public:
void exec();
}
class ConcreteStrategyB{
public:
void exec();
}
class Context{
public:
Context(AbstractStrategy* strategy):strategy_(strategy){}
~Context(){
delete strategy;
}
void run(){
strategy->exec();
}
private:
AbstractStrategy* strategy_;
Run Code Online (Sandbox Code Playgroud)
由于有指向对象的指针可能会导致不良行为,我一直在寻找一种更安全的方式来实现这种模式,我发现这个问题在哪里std::function被提议作为处理这种模式的更好方法.
有人可以更好地解释一下如何std::function运作,也许有一个战略模式的例子?
我正在尝试使用方法作为参数构建一个具有成员函数的类.这些方法在继承的类中定义.我构建了一个最小的例子:
#include <iostream>
struct base
{
base() {}
int number(int (*f)(int))
{
return f(1);
}
};
struct option1 : base
{
int timesTwo(int i){return 2*i;}
option1()
{
std::cout << number(timesTwo);
}
};
struct option2 : base
{
int timesThree(int i){return 3*i;}
int timesFour (int i){return 4*i;}
option2()
{
std::cout << number(timesThree);
}
};
int main()
{
option1 a; //I would expect this to print "2"
}
Run Code Online (Sandbox Code Playgroud)
函数中的当前语法number是针对一般函数的,但我无法使其适用于任何继承类的方法.
我试图将回调函数作为函数参数传递.但是在以下代码中获取模板替换失败错误.不确定为什么模板替换失败.
#include<iostream>
#include <map>
#include <tuple>
#include <functional>
template<typename A,typename B>
void myfun(std::map<A,B> & mm, std::function<std::tuple<A,B>(void)> fn)
{
A key;
B val;
std::tie(key,val) = fn();
mm[key] = val;
}
std::tuple<std::string,int> fun()
{
return std::make_tuple(std::string("hi"),1);
}
int main()
{
std::map<std::string,int> gg;
#if 0
//fixed version
std::function<std::tuple<std::string,int>(void)> yy = fun;//fixed
myfun(gg,yy);//fixed
#else
// error causing code
myfun(gg,fun);
#endif
}
Run Code Online (Sandbox Code Playgroud)
错误如下
main.cpp:8:6: note: template argument deduction/substitution failed:
main.cpp:25:17: note: mismatched types 'std::function<std::tuple<_T1, _T2>()>' and 'std::tuple<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> (*)()'
myfun(gg,fun);
Run Code Online (Sandbox Code Playgroud) c++ ×5
c++11 ×4
callback ×1
function ×1
inheritance ×1
lambda ×1
methods ×1
pointers ×1
std ×1
std-function ×1