I have a function that requires a function pointer as argument:
int func(int a, int (*b)(int, int))
{
return b(a,1);
}
Now I want to use a certain function that has three arguments in this function:
int c(int, int, int)
{
// ...
}
How can I bind the first argument of c so that I'm able to do:
int i = func(10, c_bound);
I've been looking at std::bind1st but I cannot seem to figure it out. It doesn't return a function pointer right? I have full freedom to adapt func so any changes of approach are possible. Althoug I would like for the user of my code to be able to define their own c...
note that the above is a ferocious simplification of the actual functions I'm using.
The project sadly requires C++98.
You can't do that. You would have to modify func to take a function-object first. Something like:
int func( int a, std::function< int(int, int) > b )
{
return b( a, rand() );
}
In fact, there is no need for b to be an std::function, it could be templated instead:
template< typename T >
int func( int a, T b )
{
return b( a, rand() );
}
but I would stick with the std::function version for clarity and somewhat less convoluted compiler output on errors.
Then you would be able to do something like:
int i = func( 10, std::bind( &c, _1, _2, some-value ) );
Note all this is C++11, but you can do it in C++03 using Boost.
Well, if you know at compile time, what you have to bind c with, you could define a new function
int c_bound(int a, int b) {
return c(a,b,some_value);
}
That's obviously not a generic solution but might solve your current problem. Otherwise K-ballo's solution seems to be the only easy generic one. However, that requires you to be able to change the signature of func. If you really have an API that you can't touch the signature, and you still need to bind an argument AND if the above solution doesn't solve your specific case: (Caution, overkill ahead) I've always wanted to use an LLVM based solution to compile a function at runtime and pass its address in such situations.
You would be unable to use a 3 argument function as a 2 argument function; Mainly because there is no real way to determine what the 3rd parameter would do.
While the above answer would work, here is another option:
If one of the parameters for c(), in use within func, is constant, you could write a wrapper function for c(int, int, int):
int d(int a, int b)
{
return c(a, b, 0); //use a constant parameter
}
or, if you can determine the 3rd parameter from the two given parameters, you can also try:
int e(int a, int b)
{
int extra = 0;
///Determine extra from a, and b
return c(a, b, c);
}
Related
Please consider the following:
typedef int (*callback_function)(int a, int b);
class receiving_callbacks_class
{
public:
static register_callback(int iterator, callback_function fn)
{
function_list[iterator] = fn;
}
private:
static callback_function function_list[10];
}
This function_list is used by a C library, so it can do call backs on certain events.
I now would like to add a routine to every callback that gets registered via this function. So that it gets called like this:
default_routine();
fn();
I tried doing it with templates, but I could not find a way to do that inside the register_callback function. Every way to do it with templates meant wrapping the function to register before calling register_callback. I would like to contain this inside this particular class.
This differs from How to add standard routine to every function in array of function pointers? by adding the requirement that no changes can be made where register_callback is called; all changes must be within receiving_callbacks_class.
This is for an embedded system where I don't have the freedom to use std. All functions passed to the register_class function will be static.
Is this possible?
First, I would like to add a preamble explaining why this is difficult in general. There is a problem involving the amount of information being stored in the C library. Other C callbacks systems store two pieces of information per callback: the address of the function to call and arbitrary data cast to void*. The function is required to accept a void* argument in addition to the arguments required by the nature of the callback. This "extra" argument receives the arbitrary data. Casting this back to its original type allows access to as much extra data as needed; it could be null if no extra data is needed. (In this case, it would be cast back to callback_function.)
In the current context, however, the only information stored in the C library is the address of a function to call. This information must be different if different callbacks are to be invoked, hence there must be different functions. The requirement that the call site not be changed means that the different functions need to be provided by receiving_callbacks_class, yet these functions need to adapt when new callbacks are written by users of receiving_callbacks_class.
I can think of four main techniques for generating multiple similar functions in C++, but one of them uses macros, so let's call it three: lambdas, templates, and copy-paste. A lambda that captures the address of the real callback is no longer convertible to a function pointer, so no longer usable with the C library. A template would use the address of the real callback as the template parameter, which means that address would have to be a compile-time constant. However, C++ does not provide a way to require that a function argument be a compile-time constant, making the approach unsuitable for use inside register_callback(). That leaves copy-paste, which normally is a pain, but might be acceptable when the number of callbacks is as small as 10.
I can base an approach on the definition of function_list. There is a smallish limit on the number of callbacks passed to the C library and they can be invoked in constant time, given their index. This approach might be less appealing if the array is replaced by a container that does not support indexed access. It definitely becomes less appealing as the size of the container increases. It might be unusable if there is not a compile-time limit on the size of the container.
To receiving_callbacks_class I might add two pieces of static data: a second array of function pointers, and a size for both of the arrays.
class receiving_callbacks_class
{
public:
// Always use a symbolic constant when a magic number is needed more than once.
static constexpr unsigned MAX_CALLBACKS = 10;
// Looks the same (but with a return type), and called the same as before.
static void register_callback(int iterator, callback_function fn)
{
function_list[iterator] = fn;
}
private:
// Old array using the new symbolic constant
static callback_function function_list[MAX_CALLBACKS];
// A new array, probably should be `const`.
static const callback_function wrapper_list[MAX_CALLBACKS];
};
The new array is for storing pointers to wrapper functions, functions that will call default_routine() followed by the real callback. This array, not the old one, is what should be given to the C library. It still needs to be initialized, though. The initialization of the new array is where copy-paste comes in. I leave it to the reader to decide how large they would let MAX_CALLBACKS get before this is considered unmanageable. Personally, I found the copy-paste to be reasonable when the size is 10.
// Initialize the new array
const callback_function receiving_callbacks_class::wrapper_list[MAX_CALLBACKS] = {
[](int a, int b) -> int { default_routine(); return function_list[0](a, b); },
[](int a, int b) -> int { default_routine(); return function_list[1](a, b); },
[](int a, int b) -> int { default_routine(); return function_list[2](a, b); },
[](int a, int b) -> int { default_routine(); return function_list[3](a, b); },
[](int a, int b) -> int { default_routine(); return function_list[4](a, b); },
[](int a, int b) -> int { default_routine(); return function_list[5](a, b); },
[](int a, int b) -> int { default_routine(); return function_list[6](a, b); },
[](int a, int b) -> int { default_routine(); return function_list[7](a, b); },
[](int a, int b) -> int { default_routine(); return function_list[8](a, b); },
[](int a, int b) -> int { default_routine(); return function_list[9](a, b); },
};
It might be appropriate to add a null check on the appropriate function_list entry; I do not know how you handle having fewer than 10 callbacks.
Note that these lambdas are non-capturing, so they do convert to function pointers. They can be non-capturing only because their number is fixed at compile-time.
The last piece to change is what I mentioned before. The call into the C library would use the new array instead of the old. This was not included in the sample code, so I'll devise a name and parameter list.
//c_library(function_list, 10); // <-- replace this
c_library(wrapper_list, MAX_CALLBACKS); // <-- with this
Not my preferred setup, but it does meet the restrictions in the question.
I have two functions with the same name but different return types. I want to run the function based on their third parameter. If the third parameter is true I want to run the first and If the parameter is false to run the second function. I was trying different things on my own because I couldn't find information online and I wasn't sure how is this called. Here is what I tried to do:
static int function(int a, int b, const bool=true);
static std::string function(int a, int b, const bool=false);
I would be grateful if someone can explain how to do this or at least give me a link to some information.
This solution is not about having two different functions but if you wanted the function to return a different type depending on the bool value using boost::any.
boost::any function(int a, int b, const bool c) {
std::string str = "Hello world!";
int num = 10;
if ( c ) {
return boost::any(num);
} else {
return boost::any(str);
}
}
This would use the third parameter in the function in order to decide which return you should do. Depending on how big function is this might be a worse solution but if you really wanted to use a boolean as a parameter I believe this should work.
Docs: Boost
Related question to this answer: Function which returns an unknown type
You can create a function template and add specializations for the different return types. Then you could use the bool argument as a template parameter:
template<bool>
auto function(int, int);
template<>
auto function<true>(int a, int b)
{
// ...
return int{};
}
template<>
auto function<false>(int a, int b)
{
// ...
return std::string{};
}
The functions would then be called like this:
int a = function<true>(1,2);
std::string b = function<false>(1,2);
Here's a demo.
Note the important caveat that the bool parameter must be known at compile time, and can't be a run time argument.
While this technique will work, do be aware that this will confuse a lot of c++ programmers. They usually expect a function to always return a particular type.
More relevant to your question; this is not actually going to make the code much more readable. Instead, having separate named functions is probably a more readable approach:
int int_function(int a, int b);
std::string str_function(int a, int b);
which could be called like this:
int a = int_function(1,2);
std::string b = str_function(1,2);
I have a member function with two arguments. Both are pointers to complex objects. When called, the function performs some non-trivial computation and then returns an integer. Like this:
struct Fooer {
int foo(const A* a, const B* b);
};
The returned integer is always the same if foo() is given the same two arguments. This function is pretty heavily used, so it would make sense to memoize its result. Normally, some lookup table with the key being the pair of pointers would suffice. However, I'm in the unique position where I know all the call sites and I know that any given call site will always use the same pair of parameters during execution. This could greatly speed up memoization if only I could pass in a third parameter, a unique integer that is basically the cache hint:
struct Fooer {
int foo(const A* a, const B* b, int pos) {
if (cached_[pos] > 0) return cached_[pos];
cached_[pos] = /* Heavy computation. */ + 1;
return cached_[pos];
}
std::vector<int> cached_;
};
What I'm looking for is a mechanism to easily generate this 'cache hint'. But nothing comes to mind. For now, I'm manually adding this parameter to the call sites of foo(), but it's obviously ugly and fragile. The function is really heavily used so it's worth this kind of optimization, in case you're wondering.
More generally, I'd like to have some kind of 'thunk' at each call site that performs the heavy lifting the first time is called, then just returns the pre-computed integer.
Note that foo() is a member function so that different instances of Fooer should have different caches.
Would this approach help you?
struct Fooer {
using CacheMap = std::map<std::pair<const A*, const B*>, int>;
std::map<int, CacheMap> lineCache;
int foo(const A* a, const B* b, int line) {
const auto key = std::make_pair(a,b);
if (linecache.count(line) > 0) {
CacheMap& cacheMap = lineCache[line];
if(cacheMap.count(key)) return cacheMap[key];
}
lineCache[line][key] = /* Heavy computation. */ + 1;
return cacheMap[key];
}
};
// Calling
foo(a, b, __LINE__)
See _ReturnAddress or any alternatives for yours compiler. Maybe you can use it in your project. Obviously, if it work for you, than just create map caller-result.
I remember vaguely that python allowed something like
def foo( x ):
....
f = foo( 5 )
Is something like that possible in c++ so that if I have a member function
class C {
void foo( int x ) { ... }
so that I can define a pointer or variable that would effectively point at foo( 5 )
The reason why I want to do this is because I have many listeners that I need to subscribe to a callback and keep information who gets called
class C {
map<int, ptrSender> m_sender;
void subscribe() {
for (const auto& p : m_sender) {
p .second->register( Callback( this, &C::onCall ) )
}
My problem is that the onCall does not return which sender called back, but I would need this information. So, instead of doing something like this
void subscribe() {
m_sender[0]->register( Callback( this, onCall_0 ) );
m_sender[1]->register( Callback( this, onCall_1 ) );
....
void onCall( int sender_id ) { ... }
void onCall_0() { onCall( 0 ); }
void onCall_1() { onCall( 1 ); }
....
I was hoping I could pass something into register that would return a call with a preset argument. Is this possible?
EDIT: I am trying to use a lambda function, but I am running into the following problems
auto setCall= [this]( int v ) { &C::onCall( v ); }
gives the compile error
lvalue required as unary&opeand
This
auto setCall= [this]( int v ) { C::onCall( v ); }
....
p.second->register( Callback( this, &setCall( p.first) ) ); /// <__ error now here
complains again, now in the second line
lvalue required as unary&operand
and this
auto setCall= [this]( int v ) { C::onCall( v ); }
....
p.second->register( Callback( this, setCall( p.first) ) ); /// <__ error now here
complains about invalid use of void expression, but I assume I have to pass in a reference to make the register function happy
Callback seems to be defined as
# define CallBack(obj,func) ProfiledBasicCallBack(obj,fastdelegate::FastDelegate0<void>(obj,func),#func)
Yes, you can use std::bind. Example usage: http://ideone.com/akoWbA.
void foo( int x ) { cout << x << endl; }
auto x = std::bind(foo, 5);
x();
However, with modern C++, you should use a lambda. Like so:
void foo( int x ) { cout << x << endl; }
auto x = []() { foo(5); };
x();
Note that this foo function is outside of the class C in this example. If you wish to contain it inside, then with std::bind you need to pass the instance of the object you wish to call on, e.g.
C c;
auto x = std::bind(&C::foo, &c, 5);
x();
or with lambdas:
C c;
auto x = [&c]() { c.foo(5); };
x();
What you are looking for is std::bind(). It takes one callable object, and gives you another callable object with predefined values for its parameter, and maybe some optional parameters forwarded to it.
A word of warning: this is a fairly steep learning curve. You need to understand templates.
If you want to bind a parameter value to a compile-time constant argument (like 5 in your example), then the problem can be solved by introducing a simple wrapper function that will call your function while passing the desired constant values as corresponding arguments.
But when the argument is a run-time value, then the answer is no: it is generally not possible to create a credible implementation of such function pointer binding in C++ (unless you are using some compiler-specific extension).
However, in C++ you have a variety of alternative tools at your disposal. You can create a function object that will mimic the functionality you desire. Such function object can be created by using std::bind, by using lambda-expressions, or even implemented manually.
The resultant function object will be "callable" and will behave similarly to function pointer at superficial level, but nevertheless it won't be a function pointer, won't be convertible to a function pointer and won't be accepted where a genuine function pointer is required. In other words, if your register method is declared to expect a function pointer as its second argument, then there's nothing you can do here. Neither std::bind, nor lambdas, nor anything else in the language will help you to achieve this kind of parameter binding.
For this reason it is generally a good idea to steer clear of function pointers in such designs and implement such functionality in terms of generic callable objects. The simplest thing to use might be std::function objects in place of raw function pointers.
I'm doing a linear genetic programming project, where programs are bred and evolved by means of natural evolution mechanisms. Their "DNA" is basically a container (I've used arrays and vectors successfully) which contain function pointers to a set of functions available.
Now, for simple problems, such as mathematical problems, I could use one type-defined function pointer which could point to functions that all return a double and all take as parameters two doubles.
Unfortunately this is not very practical. I need to be able to have a container which can have different sorts of function pointers, say a function pointer to a function which takes no arguments, or a function which takes one argument, or a function which returns something, etc (you get the idea)...
Is there any way to do this using any kind of container ?
Could I do that using a container which contains polymorphic classes, which in their turn have various kinds of function pointers?
I hope someone can direct me towards a solution because redesigning everything I've done so far is going to be painful.
A typical idea for virtual machines is to have a separate stack that is used for argument and return value passing.
Your functions can still all be of type void fn(void), but you do argument passing and returning manually.
You can do something like this:
class ArgumentStack {
public:
void push(double ret_val) { m_stack.push_back(ret_val); }
double pop() {
double arg = m_stack.back();
m_stack.pop_back();
return arg;
}
private:
std::vector<double> m_stack;
};
ArgumentStack stack;
...so a function could look like this:
// Multiplies two doubles on top of the stack.
void multiply() {
// Read arguments.
double a1 = stack.pop();
double a2 = stack.pop();
// Multiply!
double result = a1 * a2;
// Return the result by putting it on the stack.
stack.push(result);
}
This can be used in this way:
// Calculate 4 * 2.
stack.push(4);
stack.push(2);
multiply();
printf("2 * 4 = %f\n", stack.pop());
Do you follow?
You cannot put a polymorphic function in a class, since functions that take (or return) different things cannot be used in the same way (with the same interface), which is something required by polymorphism.
The idea of having a class providing a virtual function for any possible function type you need would work, but (without knowing anything about your problem!) its usage feels weird to me: what functions would a derived class override? Aren't your functions uncorrelated?
If your functions are uncorrelated (if there's no reason why you should group them as members of the same class, or if they would be static function since they don't need member variables) you should opt for something else... If you pick your functions at random you could just have several different containers, one for function type, and just pick a container at random, and then a function within it.
Could you make some examples of what your functions do?
What you mentioned itself can be implemented probably by a container of
std::function or discriminated union like Boost::variant.
For example:
#include <functional>
#include <cstdio>
#include <iostream>
struct F {
virtual ~F() {}
};
template< class Return, class Param = void >
struct Func : F {
std::function< Return( Param ) > f;
Func( std::function< Return( Param ) > const& f ) : f( f ) {}
Return operator()( Param const& x ) const { return f( x ); }
};
template< class Return >
struct Func< Return, void > : F {
std::function< Return() > f;
Func( std::function< Return() > const& f ) : f( f ) {}
Return operator()() const { return f(); }
};
static void f_void_void( void ) { puts("void"); }
static int f_int_int( int x ) { return x; }
int main()
{
F *f[] = {
new Func< void >( f_void_void ),
new Func< int, int >( f_int_int ),
};
for ( F **a = f, **e = f + 2; a != e; ++ a ) {
if ( auto p = dynamic_cast< Func< void >* >( *a ) ) {
(*p)();
}
else if ( auto p = dynamic_cast< Func< int, int >* >( *a ) ) {
std::cout<< (*p)( 1 ) <<'\n';
}
}
}
But I'm not sure this is really what you want...
What do you think about Alf P. Steinbach's comment?
This sort of thing is possible with a bit of work. First it's important to understand why something simpler is not possible: in C/C++, the exact mechanism by which arguments are passed to functions and how return values are obtained from the function depends on the types (and sizes) of the arguments. This is defined in the application binary interface (ABI) which is a set of conventions that allow C++ code compiled by different compilers to interoperate. The language also specifies a bunch of implicit type conversions that occur at the call site. So the short and simple answer is that in C/C++ the compiler cannot emit machine code for a call to a function whose signature is not known at compile time.
Now, you can of course implement something like Javascript or Python in C++, where all values (relevant to these functions) are typed dynamically. You can have a base "Value" class that can be an integer, float, string, tuples, lists, maps, etc. You could use std::variant, but in my opinion this is actually syntactically cumbersome and you're better of doing it yourself:
enum class Type {integer, real, str, tuple, map};
struct Value
{
// Returns the type of this value.
virtual Type type() const = 0;
// Put any generic interfaces you want to have across all Value types here.
};
struct Integer: Value
{
int value;
Type type() const override { return Type::integer; }
};
struct String: Value
{
std::string value;
Type type() const override { return Type::str; }
};
struct Tuple: Value
{
std::vector<Value*> value;
Type type() const override { return Type::tuple; };
}
// etc. for whatever types are interesting to you.
Now you can define a function as anything that takes a single Value* and returns a single Value*. Multiple input or output arguments can be passed in as a Tuple, or a Map:
using Function = Value* (*)(Value*);
All your function implementations will need to get the type and do something appropriate with the argument:
Value* increment(Value* x)
{
switch (x->type())
{
Type::integer:
return new Integer(((Integer*) x)->value + 1);
Type::real:
return new Real(((Real*) x)->value + 1.0);
default:
throw TypeError("expected an integer or real argument.")
}
}
increment is now compatible with the Function type and can be stored in mFuncs. You can now call a function of unknown type on arguments of unknown type and you will get an exception if the arguments don't match, or a result of some unknown type if the arguments are compatible.
Most probably you will want to store the function signature as something you can introspect, i.e. dynamically figure out the number and type of arguments that a Function takes. In this case you can make a base Function class with the necessary introspection functions and provide it an operator () to make it look something like calling a regular function. Then you would derive and implement Function as needed.
This is a sketch, but hopefully contains enough pointers to show the way. There are also more type-safe ways to write this code (I like C-style casts when I've already checked the type, but some people might insist you should use dynamic_cast instead), but I figured that is not the point of this question. You will also have to figure out how Value* objects lifetime is managed and that is an entirely different discussion.