相同的外部结构只有一个功能区别

gda*_*004 2 c++ c++11

除了修改变量之外,我有许多功能大致相同

struct example
{
    std::string name;
    std::string category;
};

using ObjName = std::string;
using Value = std::string;

bool updateName(const ObjName &name, const Value& value) ...
bool updateCategory(const ObjName &name,const Value& value)
{
    //  boost optional pointing to struct reference
    auto obj = findOjb(name);
    if (obj)
    {
        obj.get().category = value; // variable name changes 
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

我想知道的是我可以做些什么来组合代码?我怀疑它会涉及模板可能是traites/functors但我不确定如何处理任何想法?

Que*_*tin 6

重新编写Daerst的代码以删除那些可怕offsetof的指向成员的指针......

struct example
{
    std::string name;
    std::string category;
};

bool updateVariable(const ObjName &name, std::string example::*member, std::string const &value)
{
    // your code ...

    // Access
    rule.get().*member = value

    // rest of your code
}

bool updateName(const ObjName &oldname, const ObjName& newName)
{
    return updateVariable(name, &example::name, newName));
}

bool updateCategory(const ObjName &name, Category &cat)
{
    return updateVariable(name, &example::category, cat));
}
Run Code Online (Sandbox Code Playgroud)