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

时间:2015-06-28 16:32:00

标签: c++ function pointers parameters type-alias

我正在尝试书中的一些例子(lippman的c ++入门)和 我试图了解函数指针

此代码:

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

2 个答案:

答案 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;
            }
相关问题