使用可调用参数重载可调用项

Overloading on callable with callable parameter

本文关键字:调用 重载 参数      更新时间:2023-10-16

我正在尝试将下面这样的C#代码翻译成C++:

void SomeCall(Action action)
{
   // do things like action();  
}
void SomeCall(Action<Action> action)
{
   // define some action1   
   // do things like action(action1);   
}

SomeCall的C++等价物应该能够接受std::函数以及相同签名的内联和大纲C++lambda。

在浏览了许多关于C++std::function和lambdas上重载的SO问题后,似乎答案应该是:

template<typename Func>
enable_if<Func is something callable>
void SomeCall(Func&& action)
{
 ...
}
template<typename Func>
enable_if<Func is something callable taking another callable as the parameter>
void SomeCall(Func&& action)
{
 ...
}

你能帮我填空吗?

您可以尝试使用标准重载,例如:

void Fn( std::function<int(int)>& fn )
{
}
void Fn( std::function<int(float)>& fn )
{
}

如果这是不可接受的,你将不得不对模板元编程进行大量研究,以使enable_If按照你想要的方式工作,这是可以想象到的最虐待狂的编程形式。不过,严肃地说,你可以试着从安德烈·亚历山德雷斯库的《现代C++设计》开始。