8

我正在使用一个容器来保存指向任何东西的指针列表:

struct Example {
    std::vector<boost::any> elements;
}

为了在这个容器中插入元素,我编写了几个辅助函数(的成员struct Example):

void add_any(boost::any& a) {
    elements.push_back(a);
}

template<typename T>
void add_to_list(T& a) {
    boost::any bany = &a;
    add_any(bany);
}

现在,我只想在元素不存在于此容器中时插入元素。为此,我认为我只需要使用适当的比较器函数search进行调用。elements但是,我不知道如何比较boost::any实例。

我的问题: 知道我的boost::any实例总是包含指向某物的指针;是否可以比较两个boost::any值?


更新

我感谢你的回答。我还设法以一种可能不安全的方式做到了这一点:使用boost::unsafe_any_cast来获取 avoid**并比较底层指针。

目前,这工作正常。但是,我会感谢您的评论:也许这是一个大错误!

#include <boost/any.hpp>
#include <iostream>
#include <vector>
#include <string>
using namespace std;

bool any_compare(const boost::any& a1, const boost::any& a2) {
    cout << "compare " << *boost::unsafe_any_cast<void*>(&a1)
         << " with:  " << *boost::unsafe_any_cast<void*>(&a2);
    return (*boost::unsafe_any_cast<void*>(&a1)) ==
        (*boost::unsafe_any_cast<void*>(&a2));
}

struct A {};

class Example {
public:
    Example() : elements(0),
                m_1(3.14),
                m_2(42),
                m_3("hello"),
                m_4() {};
    virtual ~Example() {};

    void test_insert() {
        add_to_list(m_1);
        add_to_list(m_2);
        add_to_list(m_3);
        add_to_list(m_4);
        add_to_list(m_1); // should not insert
        add_to_list(m_2); // should not insert
        add_to_list(m_3); // should not insert 
        add_to_list(m_4); // should not insert
    };

    template <typename T>
    void add_to_list(T& a) { 
        boost::any bany = &a;
        add_any(bany);
    }

private:
    vector<boost::any> elements;
    double m_1;
    int    m_2;
    string m_3;
    A      m_4;


    void add_any(const boost::any& a) {
        cout << "Trying to insert " << (*boost::unsafe_any_cast<void*>(&a)) << endl;
        vector<boost::any>::const_iterator it;
        for (it =  elements.begin();
             it != elements.end();
             ++it) {
            if ( any_compare(a,*it) ) {
                cout << " : not inserting, already in list" << endl;
                return;
            }
            cout << endl;
        }
        cout << "Inserting " << (*boost::unsafe_any_cast<void*>(&a)) << endl;
        elements.push_back(a);
    };


};



int main(int argc, char *argv[]) {

    Example ex;
    ex.test_insert();
    unsigned char c;
    ex.add_to_list(c);
    ex.add_to_list(c); // should not insert

    return 0;
}
4

5 回答 5

4

你不能直接提供它,但你实际上可以any用作底层类型......虽然对于指针来说它是没有意义的(啊!)

struct any {
  std::type_info const& _info;
  void* _address;
};

和一个模板化的构造函数:

template <typename T>
any::any(T* t):
   _info(typeid(*t)),
   _address(dynamic_cast<void*>(t))
{
}

这是,基本上,boost::any

现在我们需要用我们的比较机制来“增强”它。

为此,我们将“捕获” std::less.

typedef bool (*Comparer)(void*,void*);

template <typename T>
bool compare(void* lhs, void* rhs) const {
  return std::less<T>()(*reinterpret_cast<T*>(lhs), *reinterpret_cast<T*>(rhs));
}

template <typename T>
Comparer make_comparer(T*) { return compare<T>; }

并增加 的构造函数any

struct any {
  std::type_info const& _info;
  void* _address;
  Comparer _comparer;
};

template <typename T>
any::any(T* t):
  _info(typeid(*t)),
  _address(dynamic_cast<void*>(t)),
  _comparer(make_comparer(t))
{
}

然后,我们提供了less(或operator<)的专业化

bool operator<(any const& lhs, any const& rhs) {
  if (lhs._info.before(rhs._info)) { return true; }
  if (rhs._info.before(lhs._info)) { return false; }
  return (*lhs._comparer)(lhs._address, rhs._address);
}

注意:封装等……留给读者作为练习

于 2011-05-17T12:06:42.900 回答
3

我能想到的唯一简单方法是对您存储在any实例中的类型进行硬编码支持,从而破坏了any...

bool equal(const boost::any& lhs, const boost::any& rhs)
{
    if (lhs.type() != rhs.type())
        return false;

    if (lhs.type() == typeid(std::string))
        return any_cast<std::string>(lhs) == any_cast<std::string>(rhs);

    if (lhs.type() == typeid(int))
        return any_cast<int>(lhs) == any_cast<int>(rhs);

    // ...

    throw std::runtime_error("comparison of any unimplemented for type");
}

使用 C++11 type_index,您可以使用 a std::mapor std::unordered_mapkeyed on std::type_index(some_boost_any_object.type())- 类似于 Alexandre 在下面的评论中建议的内容。

于 2011-05-17T10:38:00.047 回答
3

如果您可以更改容器中的类型,则有Boost.TypeErasure。它提供了简单的自定义方法any。例如,我将此类 typedef 用于类似目的:

#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/operators.hpp>

using Foo = boost::type_erasure::any<
    boost::mpl::vector<
        boost::type_erasure::copy_constructible<>,
        boost::type_erasure::equality_comparable<>,
        boost::type_erasure::typeid_<>,
        boost::type_erasure::relaxed
    >
>;

Foo行为与 完全相同boost::any,除了它可以比较相等和使用boost::type_erasure::any_cast而不是boost::any_cast.

于 2016-08-23T16:03:28.600 回答
1

也许这个算法会派上用场> http://signmotion.blogspot.com/2011/12/boostany.html

按类型和内容比较两个任意值。尝试将字符串转换为数字以获得等于。

于 2012-01-10T12:50:38.360 回答
1

无需创建新类。尝试使用 xany https://sourceforge.net/projects/extendableany/?source=directory xany 类允许向任何现有功能添加新方法。顺便说一句,文档中有一个示例可以完全满足您的要求(创建可比较的_any)。

于 2012-12-21T20:05:02.690 回答