Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function as a parameter CPP

I am attempting to call a class function in my main program that takes a function as its parameter, and applies the function to a private list. I am getting the error invalid conversion from char to char (*f)(char). Hopefully I just don't understand how to pass functions as paremeters. The following are functions in my main cpp file

char ToUpper(char c)
{
char b='A';
for(char a='a';a<='z';a++)
{
   if(a==c)
  {
     c=b;
     break;
  }
  ++b;
}
return c;
}

void upperList(LineEditor line)
{
char c;
for(int i=0;i<100;i++)   //ensure iterator is at beginning of line
  line.left();           

for(int i=0;i<100;i++)
{
  c=line.at();               //assign character current element pointed to by iterator
  line.apply(ToUpper(c));    //problem: trying to apply ToUpper function to char c
  line.right();              //apply function and increment iterator
}
}

And this is the apply member function

void LineEditor::apply(char (*f)(char c))
{
*it=f(c);
}

Also, in case it wasn't obvious, I tried using the cctypes toupper and tolower but they take and return integers.

like image 724
CChiste Avatar asked Feb 12 '26 20:02

CChiste


1 Answers

When you call ToUpper, it doesn't return the function, it returns the (supposed) character in its uppercase form.

Another reason this doesn't work is because you cannot create arguments inside the signature of a function pointer. The area for the parameter only designates the type that the function takes. This...

char (*f)(char c);
//        ^^^^^^

is therefore wrong.

Solution:

Use a std::function and std::bind it to an argument:

#include <functional>

line.apply(std::bind(ToUpper, c));

It requires the signature of apply to be changed to:

void LineEditor::apply(std::function<char (char)> f);

If you can't do this, you can simply let apply take a second parameter as the argument:

void LineEditor::apply(char (*f)(char), char c);

and call it as apply(ToUpper, c).

like image 138
David G Avatar answered Feb 15 '26 14:02

David G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!