I have the following code:
#include<iostream>
using namespace std;
typedef void (*HandlerFunc)(int, int);
HandlerFunc mr;
HandlerFunc mm()
{
return mr;
}
void sample(int a, int b, HandlerFunc func)
{
}
void main()
{
sample(1, 2, mm);
}
Here I'm trying to pass a function of type HandlerFunc to another function, but I am getting an error:
Error :*: cannot convert parameter 3 from 'void (__cdecl *(void))(int,int)' to 'void (__cdecl *)(int,int)'
If I type cast as sample(1, 2, (HandlerFunc)mm); everything works fine.
Can anyone tell what is the way to solve the error issue?
HandlerFunc mm()
{...}
should be:
void mm(int, int)
{...}
Your function sample() takes a pointer to function(you typedefd as HandlerFunc) as last argument.
The address of the function you pass as this argument must match the type of the function to which it is a pointer.
No, no, you've confused the types. mm is a function that returns a function pointer of the appropriate type. However, mm itself is not of the appropriate type - it doesn't accept any parameters.
You should pass mr in main, or pass mm() (that is - call mm and pass the return value)
The code in main should be:
sample(1,2,mm());
as mm returns a HandlerFunc, it isn't one itself.
HandlerFunc mm()
{
return mr;
}
This means nm is function which will not receive any agruments(void), and it will reutrn a pointer to function of type void (*)(int, int)
so that only you are getting that error.
Related
I'm trying to understand bind and pre-fill functions in C++.
Here's my example:
#include <iostream>
#include <functional>
#include <vector>
class Voice
{
public:
double mValue;
private:
};
class VoiceManager
{
public:
VoiceManager() { }
~VoiceManager() { }
typedef std::function<void(Voice &)> VoiceChangerFunction;
inline void UpdateVoices(VoiceChangerFunction callback) {
for (int i = 0; i < mNumOfVoices; i++) {
callback(mVoices[i]);
}
}
static void SetValue(Voice &voice, unsigned int value) {
voice.mValue = value;
std::cout << voice.mValue << std::endl;
}
private:
static const int mNumOfVoices = 4;
Voice mVoices[mNumOfVoices];
};
int main()
{
VoiceManager voiceManager;
VoiceManager::VoiceChangerFunction callback;
callback = std::bind(&VoiceManager::SetValue, std::placeholders::_1, 100);
voiceManager.UpdateVoices(callback);
}
Basically, I create a VoiceChangerFunction function (object) that takes a Voice & as first parameter and returns void.
Later, I bind a function that will take as first parameter the one I'll give to it when I call it, and another parameter that I give when I bind it (100, in my example).
Right?
What I don't understand is: then, this function is passed to UpdateVoices(), which take as input a function/object that has 1 param (Voice &), not 2 as created in my bind function (Voice &, unsigned int).
How can it works?
Its like to have void VoiceChangerFunction(Voice &voice) and call VoiceChangerFunction(Voice &voice, unsigned int value ).
The function prototype is different. I mean: the callback bind I created isn't a VoiceChangerFunctions function, because it takes more parameters.
How can it works/match?
That is exactly the beauty of bind and std::function at works. You are defining the callback as function taking one argument, and bind is returning a function object which takes one argument.
The main point here is that it actually calls the function which takes 2 parameters, but the second one is fixed, and will always be 100 (in your case). This is the sole purpose of binders - to provide a way to call functions with different set of arguments with some fixed values. If you would be calling the function taking the same set of arguments, there would be no reason to use binders at all!
Knowing that bind is similar to lambdas, the same code could be written as - and probably be more clear:
VoiceManager::VoiceChangerFunction callback;
callback = [](Voice& v) { VoiceManager::SetValue(v, 100); };
voiceManager.UpdateVoices(callback);
And if you are curious how it works, you might try to create a binder framework yourself. If you are only doing it for educational purposes and not worried about too many details, it is not that hard.
When you bind, you're making a new function that only takes Voice as a param, that's why it works.
void a_func(int x) { return; }
std::function<void(void)> new_func = std::bind(&a_func, 1);
new_func now has the signature of void(void), so you could pass it around to anywhere that expects a function of type void(void).
When you call new_func, it really calls a_func(1).
Your assumption about bind is wrong.
Your bind call returns a function object that will accept one parameter, namely the placeholder. The other parameter on your function is already bound to 100.
A little example:
void foo(int i1, int i2) {};
std::function<void(int,int)> fn1 = std::bind(foo, std::placeholders::_1, std::placeholders::_2);
std::function<void(int)> fn1 = std::bind(foo, std::placeholders::_1, 1);
std::function<void()> fn1 = std::bind(foo, 1, 1);
The bind will create a matching function depending on bound and unbound parameters.
Update
The compiler will generate a struct from the bind expression and a copy of your parameter. Simplified something like this(this will not compile):
struct Function_{
void(*fn)(Voice &, unsigned int)
unsigned int i_;
Function_(void(*f)(Voice &, unsigned int), unsigned int i):fn(f),i_(i){}
void operator()(Voice& v){
fn(v, i_);
}
}
fn is the first parameter which is a function pointer and the bound (100) is the second. Then all you need is some type erasure and your own bind is ready to go.
I am trying to pass parameters to a function pointer being passed as a parameter.
Code:
void Test(wchar_t* a, wchar_t* b)
{
// ...
}
void Test2(void(*Func)(wchar_t*, wchar_t*))
{
// ...
}
int main()
{
Test2(Test(L"Hello", L"Testing"));
return 0;
}
I am getting this error:
argument of type "void" is incompatible with parameter of type "void (*)(wchar_t *, wchar_t *)"
How do I fix this to accomplish what I'm trying to achieve?
Edit: Sorry for not being clear. What I'm actually trying to accomplish is inject a function into a child process and pass two parameters (wchar_t*, wchar_t*) so I can use them. But the main function can either be void or int argc, char** argv. So I accomplished what I'm trying to achieve by simply using global variables
You probably want to have something like
void Test2(void(*Func)(wchar_t*, wchar_t*),wchar_t* x, wchar_t* y)
{
(*Func)(x,y);
}
int main()
{
Test2(Test,L"Hello", L"Testing");
return 0;
}
instead.
As for your comment
How do i do this in C++ with templates?
I could think of
template<typename Param>
void Test2(void(*Func)(Param, Param), Param x, Param y) {
(*Func)(x,y);
}
void Test(wchar_t* a, wchar_t* b);
int main() {
Test2(Test,L"Hello", L"Testing");
return 0;
}
This should just work fine.
There are more than one way to fix tihs issue, however, let me just try to show why this error is occuring.
Every function has a type of value associated with it. This means, that every function evaluates to a value of some type. This is indicated by its return value.
For example:
int foo(/*whatever*/);
evaluates to an int. So foo(/*whatever*/) can be used anywhere an int is expected. For example like int a = b + foo(/*whatever*/).
Simlarly float bar(/*whatever*/); evaluates to a float, hence bar(/*whatever*/) can be used anywhere a float is expected. For example like float a = b + bar(/*whatever*/).
A function that returns void like void foobar(/*whatever*/) however, evaluates to void and cannot be used where a value of some type (say int, float, etc) is expected.
Now coming to code. This line in your main function has the issue:
int main()
{
Test2(Test(L"Hello", L"Testing")); /* Issue here */
return 0;
}
Here you are passing Test(L"Hello", L"Testing") as the argument to Test2. Now remember, that Test(/*whatever*/), evaluates to a void because Test returns a void.
So what you are doing in that line is something like
Test2(/*something that evaluates to a void*/);
However, Test2 expectes a void (*)(wchar_t*, wchar_t*), which is a pointer to a function that returns void, which is different from void.
So what is happening, is that the compiler is seeing that you are passing a void in a place where a void (*) (wchar_t*, wchar_t*) is expected, so it is correctly indicating that error.
There can be different ways to solve this issue which are mentioned in other answers.
Do I need to use C++ templates?
Of course, you can do that using C++ templates as it follows:
#include<utility>
// ...
template<typename F, typename... A>
void Test2(F &&f, A&&... a)
{
std::forward<F>(f)(std::forward<A>(a)...);
// ...
}
// ...
Test2(Test, L"Hello", L"Testing");
But you don't need them to do what you are trying to do.
#πάνταῥεῖ has already explained why in its answer.
I am new to Boost.Threads and am trying to understand how to pass function arguments to the boost::thread_groups::create_thread() function. After reading some tutorials and the boost documentations, I understand that it is possible to simply pass the arguments to this function but I can't get this method to work.
The other method I read about is to use functors to bind the parameters to my function but that would create copies of the arguments and I strictly require that const references be passed since the arguments will be big matrices(this I plan to do by using boost::cref(Matrix) once I get this simple example to work).
Now, let's get down to the code:
void printPower(float b, float e)
{
cout<<b<<"\t"<<e<<"\t"<<pow(b,e)<<endl;
boost::this_thread::yield();
return;
}
void thr_main()
{
boost::progress_timer timer;
boost::thread_group threads;
for (float e=0.; e<20.; e++)
{
float b=2.;
threads.create_thread(&printPower,b,e);
}
threads.join_all();
cout << "Threads Done" << endl;
}
This doesn't compile with the following error:
mt.cc: In function âvoid thr_main()â:
mt.cc:46: error: no matching function for call to âboost::thread_group::create_thread(void (*)(float, float), float&, float&)â
/usr/local/boost_1_44_0/include/boost/thread/detail/thread.hpp: In member function âvoid boost::detail::thread_data<F>::run() [with F = void (*)(float, float)]â:
mt.cc:55: instantiated from here
/usr/local/boost_1_44_0/include/boost/thread/detail/thread.hpp:61: error: too few arguments to function
What am I doing wrong?
You can't pass arguments to boost::thread_group::create_thread() function, since it gets only one argument. You could use boost::bind:
threads.create_thread(boost::bind(printPower, boost::cref(b), boost::cref(e)));
# ^ to avoid copying, as you wanted
Or, if you don't want to use boost::bind, you could use boost::thread_group::add_thread() like this:
threads.add_thread(new boost::thread(printPower, b, e));
For more flexibility you can use:
-Lambda functions (C++11): What is a lambda expression in C++11?
threads.create_thread([&b,&e]{printPower(b,e);});
-Functors that store the arguments as const references.
struct PPFunc {
PPFunc(const float& b, const float& e) : mB(b), mE(e) {}
void operator()() { printPower(mB,mE); }
const float& mB;
const float& mE;
};
-std::bind (C++11) or boost::bind
I would like to forward a callback to a function pointer. So I declare a static (int*) m_pointer1, as well as a method void RegisterCallback1( (int*)fct)
in class1.h:
public:
int RegisterCallback1( int (*fct) );
private:
static int (*m_Callback1);
in class1.cpp:
int class1::RegisterCallback1( int (*fct) )
{
m_Callback1= fct;
}
then, I want to forward the callback to the function pointer:
void class1::Callback1()
{
(*m_Callback1)();
}
But I get a compiler error "Expression must have (pointer-to)- function type
I have followed tutorial and read about function pointers and they seem to do it this way without any problems. Any ideas why?
EDIT:
So, I declare (int*)(void)m_Callback1 -Visual Studio requires a void there...-
Then how do I call the registerCallback function with the argument?
class1.RegisterCallBack1( ??? - class2::callback -??? );
static int (*m_Callback1) does not declate a function pointer, just a pointer to int: you forgot about the parameter list. You meant:
static int (*m_Callback1)();
and
int RegisterCallback1( int (*fct)() );
You haven't declared a function pointer, you've declared a normal data pointer. You are missing () at the end of the declaration.
You can try to limit the missing () errors pointed out by Oli and Dave by using a typedef for the callback function's signature: typedef int (*)() CallBack; This would at least have the merit of letting you think once about the precise number of brackets rather than at every point in your code where you use such a function.
I'm trying to call a function that takes an argument, void(*)(void*, int, const char*), but I cannot figure out how to pass those arguments to the function.
Example:
void ptr(int);
int function(int, int, void(*)(int));
I am trying to call the function like this:
function(20, 20, ptr(20));
Is this possible?
You are doing one thing incorrectly - you are trying to invoke your 'ptr' function before invoking 'function'. What you were supposed to do is to pass just a pointer to 'ptr' and invoke 'ptr' using passed pointer from 'function' like that:
void ptr(int x)
{
printf("from ptr [%d]\n", x);
}
int function(int a, int b , void (*func)(int) )
{
printf( "from function a=[%d] b=[%d]\n", a, b );
func(a); // you must invoke function here
return 123;
}
void main()
{
function( 10, 2, &ptr );
// or
function( 20, 2, ptr );
}
which gives:
from function a=[10] b=[2]
from ptr [10]
from function a=[20] b=[2]
from ptr [20]
which is what you wanted
for
function(20, 20, ptr(20));
to work - you would have to have sth like:
// 'ptr' must return sth (int for example)
// if you want its ret val to be passed as arg to 'function'
// this way you do not have to invoke 'ptr' from within 'function'
int ptr(int);
int function(int, int , int);
The usual trick is to use a typedef for signature:
typedef void signature_t (void*, int, const char*);
Notice that without the typedef the syntax is like a function declaration. It declares signature_t as a typedef for functions, so you'll always use pointers to signature_t in practice.
Then you can declare your "high-order" function as
int function (int, int, signature_t*);
See also this reply.
The correct syntax for function call is:
function(20,20, &ptr);
If you feel lost, try some tutorials, or this
Unless I totally misinterpret your code, you are trying to pass a function pointer with an argument by doing
function(20, 20, ptr(20));
That is incorrect and illegal. In order to pass a function as a parameter into another function you have to follow the following syntax
function(20, 20, &ptr);
or
function(20, 20, ptr);
Even though I would recomment leaving the '&' for readability
You can't pass ptr(20) to this function, because you can only pass the pointer to the function but not the pointer with the argument. You may read about functors and theu will help you with such problem. Or the other solution is to change the signature to
int function(int, int, void(*)(void) );
And write function
void ptr_wrap(void) {ptr(20);}
so you can call function(20, 20, ptr_wrap);. But functors can solve this problem in more elegant way.
ptr(20) is the return value of ptr, when you pass 20 to it. If you want to pass the function (and not its return value), you should write just function(20,20,ptr);