问题
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?
回答1:
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;
回答2:
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;
回答3:
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);
来源:https://stackoverflow.com/questions/36746357/typedef-function-is-not-a-type-name