[英]How to declare when passing function as parameter to function template in .cpp file?
[英]Passing a function as a parameter CPP
我试图在我的主程序中调用一个以函数作为参数的类函数,并将该函数应用于私有列表。 我收到错误invalid conversion from char to char (*f)(char)
。 希望我只是不明白如何将函数作为参数传递。 以下是我的主cpp文件中的函数
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
}
}
这是apply成员函数
void LineEditor::apply(char (*f)(char c))
{
*it=f(c);
}
此外,如果它不明显,我尝试使用cctypes toupper和tolower但他们采取并返回整数。
当您调用ToUpper
,它不返回该函数,它以大写形式返回(假定的)字符。
这不起作用的另一个原因是因为您无法在函数指针的签名内创建参数。 参数的区域仅指定函数所采用的类型。 这个...
char (*f)(char c);
// ^^^^^^
因此是错误的。
解:
使用std::function
和std::bind
它std::bind
到一个参数:
#include <functional>
line.apply(std::bind(ToUpper, c));
它要求将apply
的签名更改为:
void LineEditor::apply(std::function<char (char)> f);
如果你不能这样做,你可以简单地让apply
取第二个参数作为参数:
void LineEditor::apply(char (*f)(char), char c);
并将其称为apply(ToUpper, c)
。
表达式ToUpper(c)
调用该函数,但是当调用apply
你不想立即调用该函数,所以你需要说apply(ToUpper)
,因为ToUpper
是访问函数本身的方法。
表达式ToUpper(c)的类型是char。 所以打电话
line.apply(ToUpper(c));
表示使用char类型的参数调用函数apply。
您应该将函数定义为
void LineEditor::apply( char c, char f(char) )
{
*it=f(c);
}
没有必要重新发明轮子。 ::toupper
和::tolower
接受并返回int
,但它们的有效范围是unsigned char
。 另外, std::toupper
和std::tolower
都采用char
。
既然看起来你没有使用std::string
,我会尽量让它尽可能接近你的代码:
void upperList(LineEditor line)
{
char c;
// you do not have a begin() function??
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();
c = std::toupper(c);
line.at() = c; // assuming this returns a reference
line.right();
}
}
如果修改字符串类以使其更像std::string
类,则会变得更加容易:
std::string line;
std::transform(line.begin(), line.end(), line.begin(), std::ptr_fun<int, int>(std::toupper));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.