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

有没有办法使用模板元编程或其他东西来做到这一点?如果有帮助,我总是可以使用指针将其设为类别*。

4

1 回答 1

5

创建通用findByName模板就像用模板参数替换特定类型一样简单:

template<class T>
struct findByName
{
    string name;

    bool operator()(const T &a)
    {
        return (a.name == name);
    }
};

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

于 2010-11-27T01:33:51.693 回答