I have found myself to be in a situation where I need to pass a function to another function as an argument.
int callSomeFunction(int &func){
func();
}
If it makes any difference, callSomeFunction is a class member.
class A{
A(){}
int callSomeFunction(int &func){
func();
}
~A(){}
};
A a();
a.callSomeFunction(func);
Ideally, callSomeFunction would be able to take any kind of function.
template<typename T>
T callSomeFunction(T &func){
func();
}
I have tried many things to do this, Googled for several hours, all the standard stuff. I found these things but found them inconclusive as to the best way to accomplish this, or more appropriately the most efficient.
Resource 1
Resource 2
I like to use references over pointers where applicable, mostly because they are not a memory mess nor a syntactical mess in any cases. However, if pointers would be more applicable or a better solution, I welcome those answers as well.
Thank you, any help or pointers on how to improve the question are also appreciated should you think it may help other people as well.
This is the C++-ic way to do this: (C++ needs a 'pythonic')
The standard libraries include <functional>, a header which allows you to do this easily.
First, one must include <functional>, which provides std::function, std::placeholders, and std::bind.
A function has the following definition:
std::function<returntype(arg1type, argNtype)> f;
Unfortunately, your class or wrapper-function cannot take any kind of function, you need to know either return type or argument types, or both, of any functions you intend to use. I recommend redefining functions needed as void return type, and adding an extra argument at the end, which the output of the function sets, similar to how strcat in C works by setting the first argument equal to itself and the second argument.
void myFunction(int *arg1, float *arg2, float *returnType)
A class which could take a function defined outside of it and execute it might look something like this:
template<typename F>
class FunctionWrapper {
std::function<void(F)> f; //return type(argument type)
public:
FunctionWrapper(std::function<void(F)> _f) {
f = std::bind(_f, std::placeholders::_1); //makes f equal to _f, and does not specify an argument
}
void runFunc(F arg) { //Now send the arguments
f(arg);
}
};
The line containing bind... is the most crucial. std::bind defines an std::function as another function, and can give arguments or placeholders, in the form of std::placeholders::_N. Placeholders fulfill their namesake, they allow the programmer to bind a function with arguments of unspecified type and location/value. std::bind can also be used to simplify a function by giving certain arguments as constant ahead of time, making it easier to use in the future.
ie:
std::function<int(int,int,int)> simpleFunction;
simpleFunction = std::bind(rgbToHex(255, 127, std::placeholders::_1);
simpleFunction(153);
Now the programmer only has to specify the blue component.
I hope this helps anyone who is also having this issue! I need it to write a state machine class for my up-and-coming game... Please ask any questions you may have, I will clarify my answer if needed!
C++11 supports function pointers, such that the following is valid:
int foo()
{
}
int goo()
{
}
int main()
{
int (*pFoo)() = foo; // pFoo points to function foo()
pFoo = goo; // pFoo now points to function goo()
return 0;
}
So, for your case, you can pass the function pointer (pFoo in this example).
Code credit: http://www.learncpp.com/cpp-tutorial/78-function-pointers/
Related
The example below is a minimal, maybe not so good example of a well known idiom.
It compiles and it is so ugly in order to be able to maintain it minimal, because the question is not about the idiom itself.
struct Foo {
virtual void fn() = 0;
};
template<class T>
struct Bar: public Foo {
void fn() override {
T{}.fn();
}
};
struct S {
void fn() { }
};
int main() {
Foo *foo = new Bar<S>{};
foo->fn();
}
What I'm struggling with since an hour ago is how to change it (or even, if there exists an alternative idiom) to introduce a variadic template member method.
Obviously, I cannot modify the fn function of the Foo class, because it's a virtual one and virtual specifier doesn't goes along with templates. The same is valid for the fn specification of Bar, because it has to override somehow the one in the base class.
Note.
For I strongly suspect that this question could be one of the greatest XYProblem ever seen, I'd like also to give a brief description of the actual problem.
I have a class that exposes two templated member methods:
the first one accepts a template class T that is not used immediately, instead it should be stored somehow in order to be used later.
the second one accepts a variadic number of arguments (it is actually a variadic templated member function) and those arguments should be perfectly forwarded to a newly created instance of T.
Well, the problem is far more complex, but this is a good approximation of it and should give you an idea of what's the goal.
Edit
I guess that it is somehow similar to higher order functions.
I mean, what would solve the problem is indeed a templated function to which to bind the first argument, but as far as I know this is impossible as well as any other approach I've explored so far.
Any viable solution that expresses the same concept?
What I mentioned in the comments is the following approach:
template<typename T> class Factory {
public:
template<typename ...Args>
auto construct(Args && ...args)
{
return T(std::forward<Args>(args)...);
}
};
So now, your first exposed class method will be something like this:
template<typename T>
auto getFactory() {
return Factory<T>();
}
So:
auto factory=object.getFactory<someClass>();
// Then later:
factory.construct(std::string("Foo"), bar()); // And so on...
Instead of construct() you could use operator() too, so the second part of this becomes, simply:
factory(std::string("Foo"), bar()); // And so on...
As I mentioned, this is not really type erasure. You can't use type erasure here.
Having given this a few minutes' more thought, the reason that type erasure cannot be used here is because a given instance of type erasure must be "self contained", or atomic, and what you need to do is to break atomic type erasure into two parts, or two class methods, in your case.
That won't work. Type erasure, by definition, takes a type and "erases" it. Once your first function type-erases its class method template parameter, what you end up with is an opaque, type-erased object of some kind. What was type-erased is no longer available, to the outside world. But you still haven't type-erased your constructor parameters, which occurs somewhere else.
You can type-erase the template class, and the constructor parameters together. You can't type-erase the template class, and the constructor parameters, separately and then somehow type-erase the result again.
The simple factory-based approach, like the one I've outlined, would be the closest you can get to results that are similar to type erasure, if both halfs of your desired type-erasure appear in the same scope, so you can actually avoid type-erasure, and instead rely on compiler-generated bloat.
I also agree that you cannot do exactly what you want here. I will post what I think the closest option is (at least a close option that is different from SamVarshavchik's answer).
I don't expect this answer to solve your problem exactly, but hopefully it will give you some ideas.
struct Delay // I have no idea what to call this
{
template <class T>
void SetT()
{
function_ = [](boost::any params){return T(params);}
}
template <class ... Args>
boost::any GetT(Args ... args)
{
return function_(std::make_tuple(args...));
}
private:
std::function<boost::any(boost::any)> function_;
};
The obvious limitation of this is that anyone calling GetT will somehow have to know what T was already, though you can query the boost::any object for the type_info of its class if that helps. The other limitation here is that you have to pass in T's that take a boost::any object and know what to do with it. If you cannot have T do that, then you can change SetT (or create a new member function) like this:
template <class F>
SetTFactory(F f)
{
function_ = f;
}
and then use it like:
Delay d;
d.SetTFactory([](boost::any s){return std::string(boost::any_cast<const char*>(s));});
auto s = d.GetT("Message");
assert(s.type() == typeid(std::string));
This of course introduces a whole new set of difficulties to deal with, so I don't know how viable this solution will be for you. I think regardless of anything else, you're going to have to rethink your design quite a bit.
I've been using function pointers till now, like this format in c++. I do have some uses now and then and I'm wondering is there anything else introduced in c++11/14 as their alternative.
#include <iostream>
using namespace std;
void sayHello();
void someFunction(void f());
int main() {
someFunction(sayHello);
return 0;
}
void sayHello(){
std::cout<<"\n Hello World";
}
void someFunction(void f()){
f();
}
I did take a look at this question but couldn't understand any advantages over traditional use of function pointers. Also I would like to ask , is there anything wrong (not recommended) thing with using function pointers since I never see anyone using them. Or any other alternative present.
The question you mention suggest std::function but does not emphasize (or mentions at all) its value when combined with std::bind.
Your example is the simplest possible, but suppose you have a
std::function<void (int, int)> f ;
A function pointer can do more or less the same things. But suppose that you need a function g(int) which is f with second parameter bound to 0. With function pointers you can't do much, with std::function you can do this:
std::function<void(int)> g = std::bind(f, _1, 0) ;
As an alternative to traditional function pointers, C++11 introduced template alias which combined with variadic templates could simplify the function pointer sintax. below, an example of how to create a "template" function pointer:
template <typename R, typename ...ARGS> using function = R(*)(ARGS...);
It can be used this way:
void foo() { ... }
int bar(int) { ... }
double baz(double, float) { ... }
int main()
{
function<void> f1 = foo;
function<int, int> f2 = bar;
function<double, double, float> f3 = baz;
f1(); f2({}); f3({}, {});
return 0;
}
Also, it can deal neatly with function overloads:
void overloaded(int) { std::cout << "int version\n"; }
void overloaded(double) { std::cout << "double version\n"; }
int main()
{
function<void, int> f4 = overloaded;
function<void, double> f5 = overloaded;
f4({}); // int version
f5({}); // double version
return 0;
}
And can be used as a pretty neat way to declare function-pointers parameters:
void callCallback(function<int, int> callback, int value)
{
std::cout << "Calling\n";
std::cout << "v: " << callback(value) << '\n';
std::cout << "Called\n";
}
int main()
{
function<int, int> f2 = bar;
callCallback(f2, {});
return 0;
}
This template alias could be used as an alternative of std::function which doesn't have its drawbacks nor its advantages (good explanation here).
Live demo
As a brief, I think that template alias combined with variadic templates is a good, nice, neat and modern C++ alternative to raw function pointers (this alias still are function pointers after all) but std::function is good, nice, neat and modern C++ as well with good advantages to take into account. To stick in function pointers (or alias) or to choose std::function is up to your implementation needs.
Also I would like to ask , is there anything wrong (not recommended)
thing with using function pointers since I never see anyone using
them.
Yes. Function pointers are terrible, awful things. Firstly, they do not support being generic- so you cannot take a function pointer that, say, takes std::vector<T> for any T. Secondly, they do not support having bound state, so if at any time in the future, anybody, ever, wishes to refer to other state, they are completely screwed. This is especially bad since this includes this for member functions.
There are two approaches to taking functions in C++11. The first is to use a template. The second is to use std::function.
The template kinda looks like this:
template<typename T> void func(F f) {
f();
}
The main advantages here are that it accepts any kind of function object, including function pointer, lambda, functor, bind-result, whatever, and F can have any number of function call overloads with any signature, including templates, and it may have any size with any bound state. So it's super-duper flexible. It's also maximally efficient as the compiler can inline the operator and pass the state directly in the object.
int main() {
int x = 5;
func([=] { std::cout << x; });
}
The main downside here is the usual downsides of templates- it doesn't work for virtual functions and has to be defined in the header.
The other approach is std::function. std::function has many of the same advantages- it can be any size, bind to any state, and be anything callable, but trades a couple off. Mainly, the signature is fixed at type definition time, so you can't have a std::function<void(std::vector<T>)> for some yet-to-be-known T, and there may also be some dynamic indirection/allocation involved (if you can't SBO). The advantage of this is that since std::function is a real concrete type, you can pass it around as with any other object, so it can be used as a virtual function parameter and such things.
Basically, function pointers are just incredibly limited and can't really do anything interesting, and make the API incredibly unflexible. Their abominable syntax is a piss in the ocean and reducing it with a template alias is hilarious but pointless.
I did take a look at this question but couldn't understand any
advantages over traditional use of function pointers. Also I would
like to ask , is there anything wrong (not recommended) thing with
using function pointers since I never see anyone using them.
Normal "global" functions typically don't/can't have state. While it's not necessarily good to have state during traversal in functional programming paradigm, sometimes state might come in handy when it relates orthogonally to what has been changed (heuristics as example). Here functors (or function objects) have the advantage.
Normal functions don't compose very well (creating higher level functions of lower level functions.
Normal functions don't allow for binding additional parameters on the fly.
Sometimes normal functions can act as replacement for lambdas, and visa versa, depending on the context. Often one wouldn't want to write a special function just because you have some very local/specific requirement during "container traversal".
in C/C++ (possibly pre-C++11), is it possible to do
A (*eval(A (*function)(B), B b))(){
// ... ??
}
i.e., a function taking
a function returning an A value from a B value,
a B value to be fed to that function,
which returns
- a function returning an A from ()
...??
If yes, would it be
efficient??
guaranteed the compiler generates code
which is not executed before call of the returned function??
Thanks in advance & cheers, Nick
2014-4-20 (1): Thanks for mentioning the 'evtl.'(fixed) std::bind. :-)
So – to understand – (in C/pre C++11 without Boost) function pointers are exceptional in the way that, inside functions, it is only possible to declare them, but there is no way to produce or modify an instance – as function/method definitions are the only possible sources for function pointer instances, from where these may be handed over either explicitly, or by function/method arguments??
Just asking, as I am not clear about a possible internal representation of function pointers...
2014-4-20 (2): With the contribution of Danvil, it's time for the purpose to reveal, here the same with templates:
template<typename T,typename A>
struct Evaluator {
T(*f)(A);
A a;
T operator()() const { return f(a); }
};
template<typename T,typename A>
Evaluator<T,A> eval(T(*f)(A), A a) {
Evaluator<T,A> w;
w.f= f; w.a= a;
return w;
}
This works, while – as some already might guess – the whole, from arbitrary matching function/arguments collections, is intended to be sent as a zero parameter procedure into a single function/method handling execution similar to a try/catch.
For not having to use mostly identical code for each different parameter count, the actual idea was to generate the still not executed job as a such zero parameter procedure of same type for all cases.
Still, I do not find a way how to construct or modify a function pointer inside a function; 'typecasting' in some way to Evaluator does not seem practicable, does it??
Again, thanks a lot, and Happy Easter... :-)
I think you're looking for std::bind. The name std::bind is new, previously it was part of Boost.
#include <functional>
std::function<A (void)> curry(A (*fn)(B), B b)
{
return std::bind(fn, b);
}
Without C++11 it could work like this:
typedef A(*Func)(B);
struct Evaluator {
Func f;
B b;
A operator()() const
{ return f(b); }
};
Evaluator eval(Func f, B b) {
Evaluator w;
w.f = f;
w.b = b;
return w;
}
That's essentially what std::bind is doing, so use std::bind if you can.
What is the general idea of a delegate in C++? What are they, how are they used and what are they used for?
I'd like to first learn about them in a 'black box' way, but a bit of information on the guts of these things would be great too.
This is not C++ at its purest or cleanest, but I notice that the codebase where I work has them in abundance. I'm hoping to understand them enough, so I can just use them and not have to delve into the horrible nested template awfulness.
These two The Code Project articles explain what I mean but not particularly succinctly:
Member Function Pointers and the Fastest Possible C++ Delegates
The Impossibly Fast C++ Delegates
You have an incredible number of choices to achieve delegates in C++. Here are the ones that came to my mind.
Option 1 : functors:
A function object may be created by implementing operator()
struct Functor
{
// Normal class/struct members
int operator()(double d) // Arbitrary return types and parameter list
{
return (int) d + 1;
}
};
// Use:
Functor f;
int i = f(3.14);
Option 2: lambda expressions (C++11 only)
// Syntax is roughly: [capture](parameter list) -> return type {block}
// Some shortcuts exist
auto func = [](int i) -> double { return 2*i/1.15; };
double d = func(1);
Option 3: function pointers
int f(double d) { ... }
typedef int (*MyFuncT) (double d);
MyFuncT fp = &f;
int a = fp(3.14);
Option 4: pointer to member functions (fastest solution)
See Fast C++ Delegate (on The Code Project).
struct DelegateList
{
int f1(double d) { }
int f2(double d) { }
};
typedef int (DelegateList::* DelegateType)(double d);
DelegateType d = &DelegateList::f1;
DelegateList list;
int a = (list.*d)(3.14);
Option 5: std::function
(or boost::function if your standard library doesn't support it). It is slower, but it is the most flexible.
#include <functional>
std::function<int(double)> f = [can be set to about anything in this answer]
// Usually more useful as a parameter to another functions
Option 6: binding (using std::bind)
Allows setting some parameters in advance, convenient to call a member function for instance.
struct MyClass
{
int DoStuff(double d); // actually a DoStuff(MyClass* this, double d)
};
std::function<int(double d)> f = std::bind(&MyClass::DoStuff, this, std::placeholders::_1);
// auto f = std::bind(...); in C++11
Option 7: templates
Accept anything as long as it matches the argument list.
template <class FunctionT>
int DoSomething(FunctionT func)
{
return func(3.14);
}
A delegate is a class that wraps a pointer or reference to an object instance, a member method of that object's class to be called on that object instance, and provides a method to trigger that call.
Here's an example:
template <class T>
class CCallback
{
public:
typedef void (T::*fn)( int anArg );
CCallback(T& trg, fn op)
: m_rTarget(trg)
, m_Operation(op)
{
}
void Execute( int in )
{
(m_rTarget.*m_Operation)( in );
}
private:
CCallback();
CCallback( const CCallback& );
T& m_rTarget;
fn m_Operation;
};
class A
{
public:
virtual void Fn( int i )
{
}
};
int main( int /*argc*/, char * /*argv*/ )
{
A a;
CCallback<A> cbk( a, &A::Fn );
cbk.Execute( 3 );
}
The need for C++ delegate implementations are a long lasting embarassment to the C++ community.
Every C++ programmer would love to have them, so they eventually use them despite the facts that:
std::function() uses heap operations (and is out of reach for serious embedded programming).
All other implementations make concessions towards either portability or standard conformity to larger or lesser degrees (please verify by inspecting the various delegate implementations here and on codeproject). I have yet to see an implementation which does not use wild reinterpret_casts, Nested class "prototypes" which hopefully produce function pointers of the same size as the one passed in by the user, compiler tricks like first forward declare, then typedef then declare again, this time inheriting from another class or similar shady techniques. While it is a great accomplishment for the implementers who built that, it is still a sad testimoney on how C++ evolves.
Only rarely is it pointed out, that now over 3 C++ standard revisions, delegates were not properly addressed. (Or the lack of language features which allow for straightforward delegate implementations.)
With the way C++11 lambda functions are defined by the standard (each lambda has anonymous, different type), the situation has only improved in some use cases. But for the use case of using delegates in (DLL) library APIs, lambdas alone are still not usable. The common technique here, is to first pack the lambda into a std::function and then pass it across the API.
Very simply, a delegate provides functionality for how a function pointer SHOULD work. There are many limitations of function pointers in C++. A delegate uses some behind-the-scenes template nastyness to create a template-class function-pointer-type-thing that works in the way you might want it to.
ie - you can set them to point at a given function and you can pass them around and call them whenever and wherever you like.
There are some very good examples here:
http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible
http://www.codeproject.com/Articles/11015/The-Impossibly-Fast-C-Delegates
http://www.codeproject.com/Articles/13287/Fast-C-Delegate
An option for delegates in C++ that is not otherwise mentioned here is to do it C style using a function ptr and a context argument. This is probably the same pattern that many asking this question are trying to avoid. But, the pattern is portable, efficient, and is usable in embedded and kernel code.
class SomeClass
{
in someMember;
int SomeFunc( int);
static void EventFunc( void* this__, int a, int b, int c)
{
SomeClass* this_ = static_cast< SomeClass*>( this__);
this_->SomeFunc( a );
this_->someMember = b + c;
}
};
void ScheduleEvent( void (*delegateFunc)( void*, int, int, int), void* delegateContext);
...
SomeClass* someObject = new SomeObject();
...
ScheduleEvent( SomeClass::EventFunc, someObject);
...
Windows Runtime equivalent of a function object in standard C++. One can use the whole function as a parameter (actually that is a function pointer). It is mostly used in conjunction with events. The delegate represents a contract that event handlers much fulfill. It facilitate how a function pointer can work for.
I am trying to make a vector hold void pointers to functions, which will later be called secuentially.
So, lets say that I have got three functions. int a(), void b();, bool c();
My vector is vector<void *> vec;
And my function that stores pointers to functions.
void registerFunction(void *func)
{
vec.push_back(func);
}
Now my problem is when trying to call all the functions stored, since they are all void pointers, I just cannot call the functions without knowing their type.
So my question is... is there any way to store types of symbols so I can relate them to their respective pointers and then typecast when calling a void pointer to a function?
Note: Functions won’t be always be of type, for example, void (*)(), I will want to add methods also, hence ie. void (someclass::)(). Is it asking for too much? Should it work?
You cannot convert a function pointer to void*. It is not allowed.
If all of the functions are callable with zero arguments and you don't care about the return type, you can use std::vector<std::function<void()>> (function can also be found in Boost and TR1 if your C++ Standard Library does not support it).
Though, if I recall correctly, return-type conversion is not allowed in the C++11 std::function implementation, in which case you may need something like the following:
template <typename T>
struct ignore_result_impl
{
ignore_result_impl(T fp) : fp_(fp) { }
void operator()() { fp_(); }
T fp_;
};
template <typename T>
ignore_result_impl<T> ignore_result(T fp)
{
return ignore_result_impl<T>(fp);
}
int g() { return 42; }
std::function<void()> f(ignore_result(g));
(In the Boost implementation I know you can use function<void()> directly, but I'm pretty sure that is no longer allowed in C++11. I could be wrong and I'd appreciate clarification in the comments, if someone does know.)
void* can't safely be used as a generic pointer-to-function type (though you might be able to get away with it).
But any function-to-pointer value can be converted to another pointer-to-function type and back again without loss of information. So you can use, for example, void (*)() (pointer to function returning void and taking no arguments) as a generic pointer-to-function type.
As for storing the type, I'm not sure that's possible. If there are only a limited number of possibilities, you can use an enumeration type and a switch statement.
But you'll probably be better off using a design based on inheritance.
As long as all the functions follow the same type signature, you can cast the void pointers back to that type.
A better solution is to typedef the function type:
typedef int(*fun_ptr)();
vector<fun_ptr> vec;
Then you will not need the cast.