Question

First comes the definition of our new function object, contains_t. It could have inherited from the helper class std::unary_function (part of the C++ Standard Library, intended to facilitate the creation of the correct typedefs) and have the argument and result types defined automatically, but to make things clear, the required typedefs are provided explicitly. The argument type has changed from const boost::any& to boost::any, to avoid a potential reference-to-reference, which is illegal. The implementation is just as before, only here it is placed in the function call operator.

template <typename T> struct contains_t {
  typedef boost::any argument_type;
  typedef bool result_type;
  bool operator()(boost::any a) const {
    return typeid(T)==a.type();
  }
};

Why the following implementation has potential to receive reference-to-reference?

template <typename T> struct contains_t {
  typedef boost::any argument_type;
  typedef bool result_type;
  bool operator()(const boost::any& a) const {
    return typeid(T)==a.type();
  }
};

Thank you

Was it helpful?

Solution

Since boost::any can store anything, it can store references too. Therefore if you have a reference to a boost::any, you may accidentally end up with a reference to a reference internally.

i.e. boost::any can represent any type T. Let T be a reference of type U, i.e. T = U&. So taking a reference of the type T creates a reference to a reference of type U, which is not allowed in C++03 (C++11 will allow it though).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top