比较 boost::任何内容

发布于 2024-11-07 21:22:26 字数 2939 浏览 2 评论 0原文

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

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

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

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


更新

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

目前,这一切运行良好。不过,我很感谢您的评论:也许这是一个很大的错误!

#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;
}

I am using a container to hold a list of pointers to anything:

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

To insert elements in this container, I had written a couple of helper functions (members of the 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);
}

Now, I would like to insert elements only when they are not present in this container. To do this, I thought that I would only need to call search over elements with an appropriate comparator function. However, I do not know how to compare the boost::any instances.

My question:
Knowing that my boost::any instances always contain a pointer to something; is it possible to compare two boost::any values?


update

I thank you for your answers. I have also managed to do this in a probably unsafe way: using boost::unsafe_any_cast to obtain a void** and comparing the underlying pointer.

For the moment, this is working fine. I would, however, appreciate your comments: maybe this is a big mistake!

#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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

悲歌长辞 2024-11-14 21:22:27

我能想到的唯一简单的方法是对存储在 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 您可以使用一个std::mapstd::unordered_map 键控于 std::type_index(some_boost_any_object.type()) - 类似于 Alexandre 中的建议他的评论如下。

The only easy way to do this I can think of involves hardcoding support for the types that you're storing in the any instances, undermining much of the usefulness of 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");
}

With C++11's type_index you could use a std::map or std::unordered_map keyed on std::type_index(some_boost_any_object.type()) - similar to what Alexandre suggests in his comment below.

久光 2024-11-14 21:22:27

如果您可以更改容器中的类型,则有 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

If you can change type in container, there is Boost.TypeErasure. It provides easy way to customize any. For example I'm using such typedef for similar purpose:

#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 behaves exactly the same as boost::any, except that it can be compared for equality and use boost::type_erasure::any_cast instead of boost::any_cast.

陌上芳菲 2024-11-14 21:22:27

There is no need to create new class. Try to use xany https://sourceforge.net/projects/extendableany/?source=directory xany class allows to add new methods to any's existing functionality. By the way there is a example in documentation which does exactly what you want (creates comparable_any).

浅沫记忆 2024-11-14 21:22:27

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

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

Maybe this algorithm come in handy >
http://signmotion.blogspot.com/2011/12/boostany.html

Compare two any-values by type and content. Attempt convert string to number for equals.

挽你眉间 2024-11-14 21:22:26

你不能直接提供它,但你实际上可以使用 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: :任何

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

为此,我们将“捕获”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);
}

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

You cannot directly provide it, but you can actually use any as the underlying type... though for pointers it's pointless (ah!)

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

And a templated constructor:

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

This is, basically, boost::any.

Now we need to "augment" it with our comparison mechanism.

In order to do so, we'll "capture" the implementation of 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>; }

And augment the constructor of 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))
{
}

Then, we provided a specialization of less (or 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);
}

Note: encapsulation, etc... are left as an exercise to the reader

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文