此代码:
#include <iostream>
void useBigger (const std::string &s1, const std::string &s2,
bool (*func)(const std::string &, const std::string &))
{
bool valid = func (s1, s2);
std::cout << __func__ << " is called "
<< valid <<std::endl;
}
bool lengthCompare (const std::string &s1, const std::string &s2)
{
if (s1.size() > s2.size())
return true;
else
return false;
}
int main()
{
useBigger ("hello", "sample", lengthCompare);
return 0;
}
这段代码运行正常 但是当我尝试使用类型别名,如typedef
#include <iostream>
typedef bool func (const std::string &, const std::string &); /// or typedef bool (*func)(const std::string &, const std::string);
void useBigger (const std::string &s1, const std::string &s2,
func)
{
bool valid = func (s1, s2);
std::cout << __func__ << " is called "
<< valid <<std::endl;
}
bool lengthCompare (const std::string &s1, const std::string &s2)
{
if (s1.size() > s2.size())
return true;
else
return false;
}
int main()
{
useBigger ("hello", "hiiiii", lengthCompare);
return 0;
}
它会产生如下错误:
error: expression list treated as compound expression in functional cast [-fpermissive]
答案 0 :(得分:4)
符号func
是类型别名,但您将其用作函数。您需要实际声明一个参数变量并使用它而不是类型,例如。
void useBigger (const std::string &s1, const std::string &s2,
func f)
{
bool valid = f (s1, s2);
std::cout << __func__ << " is called "
<< valid <<std::endl;
}
答案 1 :(得分:0)
您的类型保护需要更正如下:
这
typedef bool func (const std::string &, const std::string);
要
typedef bool func (const std::string &, const std::string&);
在函数useBigger中你必须传递带有变量名的函数类型,并且需要纠正函数定义,如下所示:
void useBigger (const std::string &s1, const std::string &s2,
func f)
{
bool valid = f (s1, s2);
std::cout << __func__ << " is called "
<< valid <<std::endl;
}