简体   繁体   中英

typedef function is not a type name?

This is my code inside myCode.h :

#include <set>

using namespace std;

bool MyObjectComp(const MyObject& lhs, const MyObject& rhs) {
    return lhs.mTick < rhs.mTick;
}

typedef std::multiset<MyObject, MyObjectComp> MyObjectMultiSet;

but it says that function MyObjectComp is not a type name. Where should I place it?

The template parameter for std::multiset expects a type, MyObjectComp is not a type but is instead a function name. You can either use decltype to get its type like

typedef std::multiset<MyObject, decltype(MyObjectComp)*> MyObjectMultiSet;

Or you could specify the type yourself like

typedef std::multiset<MyObject, bool(*)(const MyObject&, const MyObject&)> MyObjectMultiSet;

Also note the generally a functor/lambda is more efficent than using a function as the compiler can more easily optimize the code. I would suggest using

struct MyObjectComp {
    bool operator()(const MyObject& lhs, const MyObject& rhs) {
        return lhs.mTick < rhs.mTick;
    }
};

typedef std::multiset<MyObject, MyObjectComp> MyObjectMultiSet;

or

auto MyObjectComp = [](const MyObject& lhs, const MyObject& rhs) {
                            return lhs.mTick < rhs.mTick;
                        };

typedef std::multiset<MyObject, decltype(MyObjectComp)> MyObjectMultiSet;

The template argument should be a type, that is why you get a compilation error. This is how you should define MyObjectComp to avoid that issue:

struct MyObjectComp {
    bool operator()(const MyObject& lhs, const MyObject& rhs) {
        return lhs.mTick < rhs.mTick;
    }
}

or you could use a lambda:

auto MyObjectComp = []()(const MyObject& lhs, const MyObject& rhs) {
    return lhs.mTick < rhs.mTick;
};

typedef std::multiset<MyObject, decltype(MyObjectComp)> MyObjectMultiSet;

Yes MyObjectComp is not type, it's function.

For this case, you might specify the template argument with type of function pointer and pass MyObjectComp as the argument of the ctor of std::multiset .

typedef std::multiset<MyObject, decltype(MyObjectComp)*> MyObjectMultiSet;
MyObjectMultiSet s(MyObjectComp);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM