c++boost-any

template copy constructor in boost::any


template copy constructor in boost::any

I am confused with these codes in any.hpp of boost.

    template<typename ValueType>
    any(const ValueType & value)
      : content(new holder<
            BOOST_DEDUCED_TYPENAME remove_cv<BOOST_DEDUCED_TYPENAME decay<const ValueType>::type>::type
        >(value))
    {   
    }

    any(const any & other)
      : content(other.content ? other.content->clone() : 0)
    { 
    }

It's clear that for the sencod copy-constructor is useful when I need a new any object from another object. But when the first copy-constucted will be executed?


Solution

  • The template constructor (which is not a copy constructor) constructs a boost::any from a const reference to some object of ValueType. The copy constructor makes a copy of an any (performing a polymorphic clone of the object within).

    Here is an example of when the first form will be selected:

    std::string s = "Hello, World";
    boost::any a(s);  // template constructor selected here
    
    boost::any b(a);  // copy constructor selected here.