本文介绍了为什么我不能将此比较函数作为模板参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用我为排序定义的函数创建一个 std::set,但我收到错误:错误:函数GFX::MeshCompare"不是类型名称"
I am trying to create an std::set with a function I defined for sorting,but I get the error: "Error: function "GFX::MeshCompare" is not a type name"
网格.h
namespace GFX
{
struct Mesh
{
[...]
};
inline bool MeshCompare(const Mesh& a, const Mesh& b)
{
return ( (a.pTech < b.pTech) ||
( (b.pTech == a.pTech) && (a.pMaterial < b.pMaterial) ) ||
( (b.pTech == a.pTech) && (a.pMaterial == b.pMaterial) && (a.topology < b.topology) )
);
}
};
渲染器.h
namespace GFX
{
class Renderer
{
private:
[...]
std::set<Mesh, MeshCompare> m_Meshes;
};
};
我做错了什么,我该如何解决?
What am I doing wrong and how do I fix it?
推荐答案
std::set
的第二个模板参数必须是 type,而不是 价值.
The second template argument to std::set
has to be a type, not value .
如果你想使用函数(它是值,而不是类型),那么你必须将它作为参数传递给构造函数,这意味着你可以这样做这个:
If you want to use function (which is value, not type), then you've to pass it as argument to the constructor, which means you can do this:
class Renderer
{
typedef bool (*ComparerType)(Mesh const&,Mesh const&);
std::set<Mesh, ComparerType> m_Meshes;
public:
Renderer() : m_Meshes(MeshCompare)
{ //^^^^^^^^^^^^^^^^^^^^^^^ note this
}
};
或者,定义一个函子类,并将其作为第二个 type 参数传递给 std::set
.
struct MeshComparer
{
bool operator()(const Mesh& a, const Mesh& b) const
{
return ( (a.pTech < b.pTech) ||
( (b.pTech == a.pTech) && (a.pMaterial < b.pMaterial) ) ||
( (b.pTech == a.pTech) && (a.pMaterial == b.pMaterial) && (a.topology < b.topology) ) );
}
};
然后使用它:
std::set<Mesh, MeshComparer> m_Meshes;
这篇关于为什么我不能将此比较函数作为模板参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!