Why can I not pass this comparison function as a template argument?

允我心安 提交于 2020-06-02 10:50:35

问题


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"

Mesh.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) ) 
               );
    }
};

Renderer.h

namespace GFX
{
    class Renderer
    {
    private:
        [...]
        std::set<Mesh, MeshCompare> m_Meshes;

    };
};

What am I doing wrong and how do I fix it?


回答1:


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
     }
};

Or, define a functor class, and pass this as second type argument to 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) ) );
   }
};

And then use it:

std::set<Mesh, MeshComparer> m_Meshes;



回答2:


If you really don't want to use a functor, you can use a pointer to function:

std::set<Mesh, bool(*)(Mesh const&, Mesh const&)> set(MapCompare);

(In this example code I'm constructing an object named set, this is not a class data member.)



来源:https://stackoverflow.com/questions/9341781/why-can-i-not-pass-this-comparison-function-as-a-template-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!