具有任何类型属性的对象,易于存储和迭代

Object with attributes of any type with easy storage and iteration

我有一个 "object",不同的属性存储为 key/value。键是一个字符串,值可以是任何基本类型。我的第一个想法是使用模板 class:

template <class T>
class Attribute {
public:
    Attribute<T>(const std::string& key, T value) :
        m_key(key),
        m_value(value)
    {
    }

    ~Attribute(){}

    T getValue() const
    {
        return m_value;
    }

    std::string getKey() const
    {
        return m_key;
    }
private:
    std::string m_key;
    T m_value;
};

但现在的问题是,在我的对象 class 中,我必须为每个可能的属性类型声明字段和重载函数:

class MyObject {
public:
    MyObject(int value) :
        m_value(value)
    {
    }

    ~MyObject()
    {
    }

    int getValue() const
    {
        return m_value;
    }

    void addAttribute(Attribute<int> attribute)
    {
        m_intAttributes.push_back(attribute);
    }

    void addAttribute(Attribute<double> attribute)
    {
        m_doubleAttributes.push_back(attribute);
    }

    const std::list<Attribute<int> >& getIntAttributes() const
    {
        return m_intAttributes;
    }

    const std::list<Attribute<double> >& getDoubleAttributes() const
    {
        return m_doubleAttributes;
    }

private:
    int m_value;
    std::list<Attribute<int> > m_intAttributes;
    std::list<Attribute<double> > m_doubleAttributes;
};

此外,遍历属性不是很舒服,查找给定名称的属性非常困难:

void showMyObject(const MyObject& myObject)
{
    std::list<Attribute<int> > intAttributes;
    std::list<Attribute<int> >::const_iterator itInt;
    std::list<Attribute<double> > doubleAttributes;
    std::list<Attribute<double> >::const_iterator itDouble;

    std::cout << "Value in myObject " << myObject.getValue() << std::endl;

    intAttributes = myObject.getIntAttributes();
    for(itInt = intAttributes.begin() ; itInt != intAttributes.end() ; itInt++)
    {
        std::cout << itInt->getKey() << " = " << itInt->getValue() << std::endl;
    }

    doubleAttributes = myObject.getDoubleAttributes();
    for(itDouble = doubleAttributes.begin() ; itDouble != doubleAttributes.end() ; itDouble++)
    {
        std::cout << itDouble->getKey() << " = " << itDouble->getValue() << std::endl;
    }
}

仅供参考,我的主要功能如下所示:

int main(int argc, char* argv[])
{
    MyObject object(123);

    object.addAttribute(Attribute<double>("testDouble", 3.23));
    object.addAttribute(Attribute<double>("testDouble2", 99.654));
    object.addAttribute(Attribute<int>("testInt", 3));
    object.addAttribute(Attribute<int>("testInt2", 99));

    showMyObject(object);

    return 0;
}

我想如果我们想保证类型安全,那么 必须有 某处带有正确 return 类型的函数列表(在我的示例中为 getTYPEAttributes) .

但是,我想知道是否存在更优雅的解决方案,以及我不知道的设计模式是否可以帮助我正确处理这个问题。

听起来像是 Boost.TypeErasure 的工作。您想存储具有共同特征(可流式传输、有密钥)但可以显式访问且不需要公共基础的不同类型的东西吗?如此存储您的属性:

namespace mpl = boost::mpl
using namespace boost::type_erasure;

BOOST_TYPE_ERASURE_MEMBER((has_getKey), getKey, 0)

using AnyAttribute = any<mpl::vector<
                         copy_constructible<>,
                         typeid_<>,
                         ostreamable<>, // add a stream operator for Attribute
                         has_getKey<std::string(), const _self>
                         > >;

std::vector<AnyAttribute> attributes;

添加属性如下所示:

template <typename T>
void addAttribute(const std::string& key, const T& value) {
    // since Attribute<T> is copy-constructible, streamable,
    // and has a member function with the signature std::string getKey() const
    // we can construct an AnyAttribute with it.
    attributes.push_back(Attribute<T>(key, value));
}

正在打印所有属性:

void showMe() {
    for (const auto& attr : attributes) {
        std::cout << attr << ' '; // since we specified ostreamable<>,
                                  // everything we put into this any<> is streamable
                                  // so the any<> is too
    }
    std::cout << '\n';
}

正在按名称和指定类型查找属性,returns nullptr 如果未找到或类型错误:

template <typename T>
const Attribute<T>* lookupAttribute(const std::string& key) {
    // can use getKey() even if they're all different types
    // because we added has_getKey<> as a concept
    auto it = std::find_if(attributes.begin(), attributes.end(), 
        [=](const AnyAttribute& a) {
            return a.getKey() == key;
        }); 

    if (it != attributes.end()) {
        // this will return a valid Attribute<T>* you specified the
        // correct type, nullptr if you specified the incorrect type
        // it is not possible to query the type.
        return any_cast<Attribute<T>*>(&*it);
    }   
    else {
        return nullptr;
    }   
}

有一个更简单的类型擦除对象,它只是 Boost.Any,但您不能拥有任何类型的通用功能 - 这将难以实现我上面说明的查找或打印操作。