可调用的可重载参数重载

可调用的可重载参数重载

本文介绍了可调用的可重载参数重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将C#代码翻译成C ++:

  void SomeCall(Action action)
{
//做类似action()的事情;

}

void SomeCall(Action< Action> action)
{
//定义一些动作1
//做动作(action1);

}



C ++相当于SomeCall应该能够采用std ::函数以及内联和大纲相同签名的C ++ lambdas。



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

 模板< typename Func> 
enable_if< Func is something callable>
void SomeCall(Func& amp; action)
{
...
}

template< typename Func>
enable_if< Func是可调用另一个可调用作为参数>
void SomeCall(FunC&&&&&&&&&&&&&&&&&&&&&>)
{
...

}
解决方案

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

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

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

如果这是不可接受的,你将不得不做模板元程序设计的大量研究来获得enable_if以你想要的方式工作,这是最可耻的编程想法。不管怎样,你可以尝试从Andrei Alexandrescu的Modern C ++ Design开始。


I am trying to translate C# code like below to C++:

void SomeCall(Action action)
{
   // do things like action();

}

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

}

C++ equivalent of SomeCall should be able to take std::function as well as inline and outline C++ lambdas of the same signature.

After browsing many SO questions regarding overloading on C++ std::function and lambdas, it seems thatthe answer should look like:

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)
{
 ...

}

Can you help me fill in the blanks?

解决方案

You can try using standard overloading like so:

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

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

If this isn't acceptable, you're going to have to do a lot of research into template meta-programming to get enable_if to work how you want, which is the most sadistic form of programming imaginable. In all seriousness though, you could try starting with Modern C++ Design by Andrei Alexandrescu.

这篇关于可调用的可重载参数重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:39