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

mor*_*ndg 3 c++ templates design-patterns

我有一个"对象",其中不同的属性存储为键/值.键是一个字符串,值可以是任何基本类型.我的第一个想法是使用模板类:

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;
};
Run Code Online (Sandbox Code Playgroud)

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

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;
};
Run Code Online (Sandbox Code Playgroud)

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

我想如果我们想要保证类型安全,那么签名中必须存在具有正确返回类型的函数列表(在我的示例中为getTYPEAttributes).

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

Bar*_*rry 5

听起来像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;
Run Code Online (Sandbox Code Playgroud)

添加属性如下所示:

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));
}
Run Code Online (Sandbox Code Playgroud)

打印所有属性:

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';
}
Run Code Online (Sandbox Code Playgroud)

按名称和指定类型查找属性,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;
    }   
}
Run Code Online (Sandbox Code Playgroud)

有一个更简单的类型擦除对象Boost.Any,但是你不能有任何类型的常用功能 - 这将使我很难实现上面说明的查找或打印操作.