Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rules for determining the set of function type compatible with std::function<R(T1,T2)>?

Suppose if I have this,

std::function<int(int,int)> fs;

then how can I determine the set of functions (or function objects) which fs can be initialized with?

Which of the folllowing is allowed and which not:

std::function<int(int,int)> fs = [](int, int) { return int(10); };
std::function<int(int,int)> fs = [](char, char) { return char(10); };
std::function<int(int,int)> fs = [](int, short) { return int(10); };
std::function<int(int,int)> fs = [](double, int) { return float(10); };
std::function<int(int,int)> fs = [](int, wchar_t) { return wchar_t(10); };

std::function<int(int,int)> fs = [](const char*, int){ return "string"; };
std::function<int(int,int)> fs = [](const char*, int){ return 10; };
std::function<int(int,int)> fs = [](const char*, int){ return std::string(); };

Of course, I can compile and see which one compiles fine, and which doesn't. But that doesn't help me understanding the variations in the types of parameters and return type. How far can I go to use different types for them?

To put it in other words, if I've given a function (or function object), how can I determine at compile-time if it is compatible with std::function<int(int,int)> or not? I've little understanding, but I'm not confident enough.

So please help me understanding and laying out the rules for determining the set of function type compatible with std::function<R(T1,T2)>? Can metaprogramming help me here to notify users, generating nice error messages, if they use incompatible function?

By the way, the first group seems to be compatible : http://ideone.com/hJpG3

like image 888
Nawaz Avatar asked Nov 28 '11 15:11

Nawaz


1 Answers

The object (function pointer or functor) must be Callable with the given argument types, i.e. fun( declval< Types >() ... ) is well-formed and implicitly convertible to R.

See C++11 §20.8.2 in particular; it gives various special cases for pointers-to-members, etc. §20.8.11.2/2 and 20.8.11.2.1/7 tie this to the std::function constructor.

like image 176
Potatoswatter Avatar answered Sep 26 '22 05:09

Potatoswatter