C++11 如何传递函数指针和lambda';它使用一个接口

C++11 如何传递函数指针和lambda';它使用一个接口,c++11,lambda,C++11,Lambda,我试图使用一个接口将函数指针和lambda一起使用。我决定使用std::function,但我很快发现它无法单独处理重载函数 例如: void foobar(double i_double ){std::cout << "double argument" << i_double << std::endl;} void foobar(){std::cout << "no argument" << std::endl;} void foob

我试图使用一个接口将函数指针和lambda一起使用。我决定使用
std::function
,但我很快发现它无法单独处理重载函数

例如:

void foobar(double i_double ){std::cout << "double argument" << i_double << std::endl;}
void foobar(){std::cout << "no argument" << std::endl;}
void foobar(int){std::cout << "int argument" << std::endl;}

std::function<void(double)> func = static_cast<void(*)(double)>(&foobar);

目前,此CIteratorFilter需要实现函数指针和
std::function
接口,我认为这不是很好。

为什么不使用带有正确参数的非捕获lambda,并调用
foobar
函数

std::function func=[](双d){foobar(d);};
这是我能想到的最好的了。

看。。。一个XY问题

不需要这样或类似的东西:

std::function<void(double)> func = static_cast<void(*)(double)>(&foobar);
std::function func=static\u cast(&foobar);
您需要使用以下模板:

template <class Func>
CIteratorFilter<String>( listofstrings, Func func) {
  // call func whatever it may be function pointer, lambda, callable object:
  func(..whatever params...);
}
模板
CIteratorFilter(列表字符串,Func Func){
//调用func,无论它是函数指针、lambda还是可调用对象:
func(…任何参数…);
}

如果您想使用C++11功能和宏魔术,您可以对
func
使用perfect fowarding

#define FUNCTION(RETURN, NAME, ...) \
  std::function<RETURN (__VA_ARGS__)>(static_cast<RETURN(*)(__VA_ARGS__)>(&NAME))
如果您不想使用变量参数,下面是另一种方法:

#define FUNCTION(RETURN, NAME, PARAMETERS) \
  std::function<RETURN PARAMETERS>(static_cast<RETURN(*)PARAMETERS>(&NAME))

告诉我们你打算如何使用这个。它看起来像一个XY问题,甚至更好:
auto func=
我想我应该提到,目前已经存在一个大型框架。。这意味着我需要用lamba's everywhere重写所有代码,这很难看,在我看来不需要。CIteratorFilter本身就是模板,我能使构造函数模板化,并将参数转发给基类构造函数吗?实际上,你的语法不是有效的C++,所以我尽可能地猜测你的代码实际上是如何看起来的。这是可能的。Post-actual code(非常小但可编译)Hm我尝试过这样做,但是CIteratorFilter上的模板构造函数对于重载方法的函数指针不再有效。。与之前相同的问题:(为此,请使用将其包装在lambda中提供的解决方案
#define FUNCTION(RETURN, NAME, ...) \
  std::function<RETURN (__VA_ARGS__)>(static_cast<RETURN(*)(__VA_ARGS__)>(&NAME))
auto func1 = FUNCTION(void, foobar, double);
auto func2 = FUNCTION(void, foobar);
auto func3 = FUNCTION(void, foobar, int);
#define FUNCTION(RETURN, NAME, PARAMETERS) \
  std::function<RETURN PARAMETERS>(static_cast<RETURN(*)PARAMETERS>(&NAME))
auto func1 = FUNCTION(void, foobar, (double));
auto func2 = FUNCTION(void, foobar, ());
auto func3 = FUNCTION(void, foobar, (int));