Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...