c++ - 为什么我不能将这个比较函数作为模板参数传递?

标签 c++ stl std

我正在尝试创建一个 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/

相关文章:

c++ - 模板化 std::future 返回问题

c++ - 带有 vector 的新运算符

即使是静态链接的 C++ 请求 MSVCP110D.dll

c++ - 无法使用对类型键设置映射值

c++ - std::map.find 上的 Sigbus

c++ - namespace std 在哪里定义的?

c++ - 不抛出 std::out_of_range 异常

c++ - 如何使用 CMake 从根文件夹外部添加包含目录?

c++ - 为什么我收到 clang 警告 : no previous prototype for function 'diff'

c++ - 在构造期间使用单例管理指针?