Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c++ - how to make std::function instance

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...