|
Boost : |
From: vonosan (5045-2h8p_at_[hidden])
Date: 2002-01-15 03:11:58
Hi,
(I didn't followed discussion for any,
so my proposals may already been discussed)
Class any contributed by Kevlin Henney
has abstract placeholder class inside
and holder templates derived from placeholder.
IMO, placeholder and holder can be moved to
template parameters:
| template<
| class placeholder = default_placeholder,
| template<typename> class holder = default_holder>
| class basic_any;
Addinionally, operator-> can be added:
| // ... (template parameters)
| class basic_any
| {
| placeholder * operator->() { return content; }
| // ...
| };
Now user can customize placholder. He or she can add
new function to the placeholder:
| class io_placeholder
| {
| // ... (impl of placeholder requirements)
| virtual void write(ostream &) const = 0;
| };
then implement it in io_holder:
| template<typename T>
| class io_holder
| {
| T val_;
| // ... (impl of io_placeholder virtual functions)
| virtual void write(ostream & os) const { os << val_; }
| };
define alias:
| typedef basic_any<io_placeholder, io_holder> io_any;
and use:
| io_any a("Hello");
| a->write(cout);
Why it's better? Besause you avoid error-prone if-else-if:
| any a("Hello");
| if(a.type() == typeid(int))
| cout << any_cast<int>(a);
| else if(a.type() == typeid(const char *))
| cout << any_cast<const char *>(a);
| // ... (else if for other types)
With this class you can implement holder with
virtual functions from your problem domain and
call they like I did.
One problem is still open: how to implement read from
istream operation using prefixes and make-functions?
Other proposal is adding buffer_size to the basic_any
class as third template parameter with default value 0.
Only dynamic allocations will take place for basic_any
with default buffer_size. If buffer_size is greater
then 0 then for every type T that has:
| sizeof(holder<T>) <= buffer_size
buffer defined inside basic_any will be
used for allocations.
-----------------
Alexander Nasonov
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk