具有类型别名的函数指针参数

function pointer parameter with type alias

我正在尝试书中的一些示例(lippman 的 c++ primer)和 我正在尝试了解函数指针

此代码:

#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]

符号 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;
        }

您的类型定义需要更正如下:

来自

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;
            }