why do we need a generic type specified in Boost library? Isn’t template enough?
Fore example, if I want a container of a specific type, I would just do:
template<class Type>
vector<Type> v;
If I want to specify a container which contains everything, I simply write:
vector v;
In explanation for boost::any (http://www.boost.org/doc/libs/1_46_1/doc/html/any/s02.html)
Converting types that can hold one of
a number of possible value types, e.g.
int and string, and freely convert
between them, for instance
interpreting 5 as “5” or vice-versa.
Such types are common in scripting and
other interpreted languages.
boost::lexical_cast supports such
conversion functionality.
Why do we need implicit type like in scripting languages such as PHP?
Further more, in the boost::any example, why:
using boost::any_cast;
typedef std::list<boost::any> many;
void append_int(many & values, int value)
{
boost::any to_append = value;
values.push_back(to_append);
}
is acceptable? Does the container use the operator = implemented in boost::any?
any & operator=(const any &);
which makes boost::any able to hold any type? Operator = defined in boost::any is explained as:
Effects: Copies content of rhs into
current instance, discarding previous
content, so that the new content is
equivalent in both type and value to
the content of rhs, or empty if
rhs.empty().Throws: std::bad_alloc or any
exceptions arising from the copy
constructor of the contained type.
Assignment satisfies the strong
guarantee of exception safety.
http://www.boost.org/doc/libs/1_46_1/doc/html/boost/any.html
Because C++ does not have generic type. It has type templates, which are compiled for each substituted type separately. The expression
is a syntax error, because vector is not a class (it’s a class template that can be instantiated to class by giving it template parameters).
There is a somewhat generic type in C++, the
void*, but then it’s your responsibility to remember what you stored in it (esp. for purposes of deletion). Theboost::anyis a typesafe alternative that remembers what you stored there and will give an error if you try to convert it to something it does not have defined conversion to (you still have to ask it for the actual value byany_cast).As for
operator=, yes, it is used by the container. The standard containers generally require the element type to be default constructible and assignable, which means they need to have working copy constructor and assignment operator. They generally either don’t have to be default constructible or only have to be default constructible if you use certain operations.