在不使用decltype[c++]的情况下为键类型传递比较函数

Pass a comparison function for Key Type without using decltype[c++]

本文关键字:类型 函数 比较 情况下 decltype c++      更新时间:2023-10-16

想知道如何在不使用decltype的情况下,将指向函数的指针作为比较函数作为Key Type传递。

使用decltype

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

不使用decltype

std::multiset<Sales_data, (bool (*pf)(const Sales_data &, const Sales_data &)> bookstore(&compareIsbn);

尽管会弹出错误。

    Testing.cpp:15:36: error: use of undeclared identifier 'pf'
        std::multiset<Sales_data, (bool (*pf)(const Sales_data &, const Sales_data &)> ...
                                          ^
Testing.cpp:15:40: error: expected expression
        std::multiset<Sales_data, (bool (*pf)(const Sales_data &, const Sales_data &)> ...
                                              ^
Testing.cpp:15:60: error: expected expression
        std::multiset<Sales_data, (bool (*pf)(const Sales_data &, const Sales_data &)> ...
                                                                  ^
Testing.cpp:15:81: error: use of undeclared identifier 'bookstore'
        std::multiset<Sales_data, (bool (*pf)(const Sales_data &, const Sales_data &)> bookstor...
                                                                                       ^
Testing.cpp:15:104: warning: declaration does not declare anything [-Wmissing-declarations]
  ...(bool (*pf)(const Sales_data &, const Sales_data &)> bookstore(&compareIsbn);
                                                                                 ^
1 warning and 4 errors generated.

任何帮助都将不胜感激,谢谢!

您不需要名称参数-您只需要类型:

std::multiset<Sales_data, 
               bool (*)(const Sales_data &, const Sales_data &)
               > bookstore(&compareIsbn);

您所做的是声明一个名为pf类型的函数指针。

您也不需要&,只需要compareIsbn即可。