且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我不能将此比较函数作为模板参数传递?

更新时间:2022-04-04 23:57:57

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;