typedef函数不是类型名称吗? [英] typedef function is not a type name?
本文介绍了typedef函数不是类型名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我在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;
,但它表示函数MyObjectComp
不是类型名称.我应该放在哪里?
but it says that function MyObjectComp
is not a type name. Where should I place it?
推荐答案
std::multiset
的模板参数需要一个类型,MyObjectComp
不是类型,而是函数名.您可以使用decltype
获取其类型,例如
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;
还要注意,函子/lambda通常比使用函数更有效,因为编译器可以更轻松地优化代码.我建议使用
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;
或
auto MyObjectComp = [](const MyObject& lhs, const MyObject& rhs) {
return lhs.mTick < rhs.mTick;
};
typedef std::multiset<MyObject, decltype(MyObjectComp)> MyObjectMultiSet;
这篇关于typedef函数不是类型名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文