简体   繁体   English

typedef函数不是类型名称吗?

[英]typedef function is not a type name?

This is my code inside myCode.h : 这是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. 但是它说函数MyObjectComp不是类型名称。 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. std::multiset的模板参数需要一个类型, MyObjectComp不是类型,而是函数名称。 You can either use decltype to get its type like 您可以使用decltype来获取其类型,例如

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. 还要注意,函子/ lambda通常比使用函数更有效,因为编译器可以更轻松地优化代码。 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. template参数应该是一种类型,这就是为什么会出现编译错误的原因。 This is how you should define MyObjectComp to avoid that issue: 这是您应定义MyObjectComp以避免这种问题的方式:

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

or you could use a lambda: 或者您可以使用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. 是的, MyObjectComp不是类型,而是函数。

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 . 对于这种情况,您可以使用函数指针的类型指定模板参数,并将MyObjectComp传递为std::multiset的ctor的参数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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