代码之家  ›  专栏  ›  技术社区  ›  Jookia

模板元编程?

  •  -1
  • Jookia  · 技术社区  · 15 年前
    struct findCategoryByName
    {
        string name;
    
        bool operator()(const category& a)
        {
            return (a.name == name);
        }
    };
    
    struct findEntryByName
    {
        string name;
    
        bool operator()(const entry* a)
        {
            return (a->name == name);
        }
    };
    

    有没有一种方法可以使用模板元编程或其他什么?如果有帮助的话,我可以用一个指针来分类。

    1 回复  |  直到 15 年前
        1
  •  5
  •   sth    15 年前

    创建泛型 findByName 模板只需用模板参数替换特定类型即可:

    template<class T>
    struct findByName
    {
        string name;
    
        bool operator()(const T &a)
        {
            return (a.name == name);
        }
    };
    

    (这假定参数是通过引用传递的,但如果愿意,可以将其更改为以指针作为参数。)

    推荐文章