im trying some examples in a book(c++ primer by lippman) and im trying to learn about function pointers
this code:
#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;
}
this code just runs fine but when i try using type alias such as 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;
}
it produces an error something like this:
error: expression list treated as compound expression in functional cast [-fpermissive]
The symbol func
is a type alias , but you use it as a function. You need to actually declare an argument variable and use it instead of the type, like eg
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;
}
Your type defenition need to correct as follows:
From
typedef bool func (const std::string &, const std::string);
TO
typedef bool func (const std::string &, const std::string&);
And in function useBigger you have to pass the function type with variable name and need to correct function definition as follows:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.