在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.
更多推荐
发布评论