简体   繁体   English

输入std :: function的别名

[英]Type alias for std::function

I'm trying to alias the std::function type because I plan on using something else in the future. 我正在尝试为std::function类型添加别名,因为我计划将来使用其他std::function And I would like to be able to easily make that change. 我希望能够轻松进行更改。 But I'm getting an error message from the compiler that I don't really understand. 但是我从编译器中收到了一个我不太了解的错误消息。 I understand what it means but I don't understand it in this context. 我理解这意味着什么,但在这种情况下我不理解。

Example: 例:

#include <functional>

template < typename Ret, typename... Args > using MyFunc = std::function< Ret(Args...) >;

int main(int argc, char **argv)
{
    MyFunc<void(int)> fn;

    return 0;
}

Generates: 产生:

..\main.cpp|7|required from here|
..\main.cpp|3|error: function returning a function|
template <typename F>
using MyFunc = std::function<F>;

void(int) is a single (function) type. void(int)是单个(函数)类型。

Even though the accepted response is right, it proposes a slightly different approach in regard of the one the OP posted. 即使已接受的答复是正确的,但对于OP所发布的答复,它还是提出了一种略有不同的方法。

For the sake of clarity, it must be said that also the solution the OP was using is fine. 为了清楚起见,必须说OP使用的解决方案也很好。
The problem is how he was using the MyFunc type in his main function. 问题是他在main功能中如何使用MyFunc类型。

It shouldn't be: 它不应该是:

MyFunc<void(int)> fn;

Instead, the following one is right: 相反,以下一项是正确的:

MyFunc<void, int> fn;

Because of that, the code below works as expected: 因此,以下代码可以正常工作:

#include <functional>

template < typename Ret, typename... Args >
using MyFunc = std::function< Ret(Args...) >;

int main(int argc, char **argv) {
    MyFunc<void, int> fn; // it was MyFunc<void(int)> fn;
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM