How to define a multiset using a function pointer?

强颜欢笑 提交于 2021-02-07 08:51:22

问题


I'm stuck when doing an exercise from C++ Primer 5th Edition ,which goes like

Exercise 11.11: Redefine bookstore without using decltype.

Below is the relevant codes in this book:

multiset<Sales_data, decltype(compareIsbn)*> bookstore(compareIsbn);

The code for class Sales_data is a little bit verbose to post here,so I wrote a simpler one and defined the multiset in the same style, as shown below. It compiled without any error.

class A
{
    int lenth;
public:
    int getLenth() const {return lenth;}
};

bool compareA(const A &a1, const A &a2)
{
    return a1.getLenth() < a2.getLenth();
}

int main()
{
    std::multiset<A, decltype(compareA)*> m1(compareA);
    return 0;
}

I guess this exercise want readers to review knowledge of function pointers, so I tried another way to define it. But it doesn't work. Below is where I'm stuck

int main()
{
    bool (*fp) (const A &a1, const A &a2);
    fp = &compareA;

    std::multiset<A, fp*> m1(fp);

    return 0;
}

Three errors were generated:

error: template argument 2 is invalid
error: invalid type in declaration before '(' token
error: invalid conversion from 'bool (*)(const A&, const A&)' to 'int' [-fpermissive]

What's my problem?How to fix it?


回答1:


You were close, but needed a type arguement in the open <> brackets rather than a pointer

typedef bool (*fp) (const A &a1, const A &a2);
int main() {    
    std::multiset<A, fp> m1(&compareA);

    return 0;
}

Or

bool (*fp) (const A &a1, const A &a2) = compareA;
int main() {    
    std::multiset<A, bool (*) (const A &, const A &)> m1(fp);

    return 0;
}

With a more recent compiler, you can define the comparator inline through the use of higher-order functions:

using comparator = std::function<bool(const A&, const A&)>;

auto main() -> int {    
    std::multiset<A, comparator> m1([](const A& a1, const A& a2) -> bool {
         return a1.getLenth() < a2.getLenth();
    });
    return 0;
}



回答2:


The second template argument of std::multiset expects a type of a function, not a function !

This will work:

#include <set>

struct A{};

bool compareA(const A &a1, const A &a2)
{
    return true;
}

int main()
{
    std::multiset<A, bool (*)(const A&, const A&)> m1(compareA);

    // or

    typedef bool (*fp)(const A&, const A&);

    std::multiset<A, fp> m2(compareA);
}


来源:https://stackoverflow.com/questions/20627530/how-to-define-a-multiset-using-a-function-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!