C#转换为C++ 11:委托模板

Mik*_*hke 5 c# c++ templates c++11

我正在尝试将此C#代码转换为C++:

public delegate void Action<in T>(T obj);
public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2);
public delegate void Action<in T1, in T2, in T3>(T1 arg1, T2 arg2, T3 arg3);
Run Code Online (Sandbox Code Playgroud)

非常清楚这需要std :: function.由于这是一个较大的项目,我使用工具进行所有转换,这就是它提出的:

#include <functional>

    template<typename T>
//C# TO C++ CONVERTER TODO TASK: C++ does not allow specifying covariance or contravariance in a generic type list:
//ORIGINAL LINE: public delegate void System::Action<in T>(T obj);
    using std::function<void()> = std::function<void (T obj)>;

    template<typename T1, typename T2>
//C# TO C++ CONVERTER TODO TASK: C++ does not allow specifying covariance or contravariance in a generic type list:
//ORIGINAL LINE: public delegate void System::Action<in T1, in T2>(T1 arg1, T2 arg2);
    using std::function<void()> = std::function<void (T1 arg1, T2 arg2)>;

    template<typename T1, typename T2, typename T3>
//C# TO C++ CONVERTER TODO TASK: C++ does not allow specifying covariance or contravariance in a generic type list:
//ORIGINAL LINE: public delegate void System::Action<in T1, in T2, in T3>(T1 arg1, T2 arg2, T3 arg3);
    using std::function<void()> = std::function<void (T1 arg1, T2 arg2, T3 arg3)>;
Run Code Online (Sandbox Code Playgroud)

我假设使用std::function<void()>是一个翻译错误,所以我把它们改为Action.所以,我的最终版本是这样的:

template<typename T>
using Action = std::function<void(T obj)>;

template<typename T1, typename T2>
using Action = std::function<void(T1 arg1, T2 arg2)>;

template<typename T1, typename T2, typename T3>
using Action = std::function<void(T1 arg1, T2 arg2, T3 arg3)>;
Run Code Online (Sandbox Code Playgroud)

但是这不能编译,可以理解的错误是已经定义了Action(当使用第二行时到达).但是,有可能让模板函数具有重载(同名,不同的模板参数),所以我想知道为什么这对我的别名模板不起作用.它根本不受支持还是我错过了什么?

另外,也许我没有完全理解共同和逆变,但在我看来它们不适用于这个问题(这里没有涉及类型继承),所以我看不出转换器工具想通过这些注释告诉我什么.

Mik*_*hke 1

JoachimPilebord 不想回答,所以为了完整起见我这样做了。解决方案是使用模板参数包如下

template<typename ... Ts>
using Action = std::function < void(Ts...) >;
Run Code Online (Sandbox Code Playgroud)

它允许使用任意数量的参数定义回调函数。您可以使用 std::bind 进行类似的操作,但这样代码更干净且更易于阅读。