1

I have a vector of boost::any and would like to find the index of a 'any' in this vector.

Something like this :

vector<any> values;
any valueISearch = ...;
find<A*>(valueISearch);

For this I try to compare 2 any values with the following method :

    template <class T> bool IsValueEqualTo(any aniInVector, any value)
 {
  if (aniInVector.empty() && value.empty())
   return true;

  if (aniInVector.empty() && !value.empty())
   return false;

  if (!aniInVector.empty() && value.empty())
   return false;

  try
  {
   T left = boost::any_cast<T>(aniInVector);
   T right = boost::any_cast<T>(value);

   return left == right;
  }
  catch(const boost::bad_any_cast &exception)
  {
  }

  return false;
 }

The problem is that now when I do a anycast it only cast to the specific type and don't care about base types :

class A {};
class B: public A {};
B v1;
B v2;
IsValueEqualTo<A*>(&v1, &v2);
manlio
  • 18,345
  • 14
  • 76
  • 126
Spectral
  • 717
  • 2
  • 12
  • 28

3 Answers3

1

I think your problem is that there is a fundamental limitation in the boost::any library that causes these sorts of casts to fail. More generally, you can only recover an object from a boost::any using any_cast if you try to retrieve an object of identical type. For example, this doesn't work:

class A { ... };
class B: public A { ... };

boost::any a = new B*;
A* ptr = boost::any_cast<A*>(a); // Cast fails

This is something that people have been complaining about for a while and I don't know a workaround. I think that one thing you might want to do is consider why you're mixing boost::any with polymorphism in the first place. It's quite possible that you absolutely must do this, but I don't see a good way to fix this without minimizing your use of boost::any.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
0

Try using 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).

ArmanHunanyan
  • 905
  • 3
  • 11
  • 24
0

This algorithm compares two boost::any values by type and content (attempt convert string to number for equals - lazy equals :) http://signmotion.blogspot.com/2011/12/boostany.html