如何使std :: function实例(how to make std::function instance)

编程入门 行业动态 更新时间:2024-10-28 12:29:04
如何使std :: function实例(how to make std::function instance)

在C ++ 0x中,我们使用如下的use std::function :

int normal_function() { return 42; } std::function<int()> f = normal_function;

所以要得到一个std::function实例,我们必须首先定义它的类型。 但它很无聊,有时很难。

那么,我们能不能像std::tuple一样使用make来获得一个std::function实例?

事实上,我刚刚搜索了一下,C ++ 0x并没有提供这样的make工具。

为什么C ++ 0x不提供make设备? 我们可以执行它吗?

In C++0x, we use use std::function like the following:

int normal_function() { return 42; } std::function<int()> f = normal_function;

So to get an std::function instance, we have to define its type firstly. But it's boring and sometimes hard.

So, can we just use make to get a std::function instance just like std::tuple?

In fact, I just googled, C++0x doesn't provide such make facility.

Why C++0x no provide make facility? Can we implement it?

最满意答案

是的,我们可以实施它

template<typename T> std::function<T> make_function(T *t) { return { t }; }

这要求你将一个函数传递给make_function 。 为了防止超载将其替换为普通函数以外的其他内容,可以使用SFINAE

template<typename T> std::function< typename std::enable_if<std::is_function<T>::value, T>::type > make_function(T *t) { return { t }; }

你不能传递类类型函数对象,也不能传递成员指针。 对于任意函数对象,无法获得呼叫签名(如果相应的operator()是模板,你会怎么做?)。 这可能是C ++ 11没有提供这种功能的原因。

Yes we can implement it

template<typename T> std::function<T> make_function(T *t) { return { t }; }

This requires that you pass a function to make_function. To prevent overload to pick this up for something other than a plain function, you can SFINAE it

template<typename T> std::function< typename std::enable_if<std::is_function<T>::value, T>::type > make_function(T *t) { return { t }; }

You cannot pass it class type function objects though and no member pointers. For arbitrary function objects there is no way to obtain a call signature (what would you do if the respective operator() is a template?). This probably is the reason that C++11 provides no such facility.

更多推荐

本文发布于:2023-07-15 21:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1119278.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   std   function   instance

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!