我正在尝试创建一个 std::set,其中包含我为排序定义的函数, 但我收到错误:“错误:函数“GFX::MeshCompare”不是类型名称”
网格.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;
};
};
我做错了什么,我该如何解决?
最佳答案
std::set
的第二个模板参数必须是类型,而不是值。
如果你想使用函数(它是值,而不是类型),那么你必须将它作为参数传递给构造函数,这意味着你可以这个:
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;
关于c++ - 为什么我不能将这个比较函数作为模板参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9341781/