Doc. no.   WG21/N1939=J16/06-0009
Date:        2006-02-24
Project:     Programming Language C++
Reply to:   Kevlin Henney <kevlin@curbralan.com>
                Beman  Dawes <bdawes@acm.org>

Any Library Proposal for TR2

Introduction

This paper proposes addition of a library component to the C++ Standard Library Technical Report 2. The proposal is based on the Boost Any Library (see www.boost.org/libs/any).

The library provides a type-safe container for single values of value types. The Boost version of the library is widely used. The library would be a pure addition to the C++ Standard Library TR2.

There are times when a generic (in the sense of general as opposed to template-based programming) type is needed: variables that are truly variable, accommodating values of many other more specific types rather than C++'s normal strict and static types. We can distinguish three basic kinds of generic type:

  1. 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.
     
  2. Discriminated types that contain values of different types but do not attempt conversion between them, i.e. 5 is held strictly as an int and is not implicitly convertible either to "5" or to 5.0. Their indifference to interpretation but awareness of type effectively makes them safe, generic containers of single values, with no scope for surprises from ambiguous conversions.
     
  3. Indiscriminate types that can refer to anything but are oblivious to the actual underlying type, entrusting all forms of access and interpretation to the programmer. This niche is dominated by void *, which offers plenty of scope for surprising, undefined behavior.

The proposed any class (based on the class of the same name described in "Valued Conversions" by Kevlin Henney, C++ Report 12(7), July/August 2000) is a variant value type based on the second category. It supports copying of any value type and safe checked extraction of that value strictly against its type.

A similar design, offering more appropriate operators, could be used for a generalized function adaptor, a generalized iterator adaptor,  and other object types that need uniform runtime treatment but support only compile-time template parameter conformance. Such components are not proposed here.

Examples

The following code demonstrates the syntax for using implicit conversions to and copying of any objects:

#include <list>
#include <any>

using std::tr2::any_cast;
using std::tr2::any;

typedef std::list<any> many;

void append_int(many & values, int value)
{
    any to_append = value;
    values.push_back(to_append);
}

void append_string(many & values, const std::string & value)
{
    values.push_back(value);
}

void append_char_ptr(many & values, const char * value)
{
    values.push_back(value);
}

void append_any(many & values, const any & value)
{
    values.push_back(value);
}

void append_nothing(many & values)
{
    values.push_back(());
}

The following predicates follow on from the previous definitions and demonstrate the use of queries on any objects:

bool is_empty(const any & operand)
{
    return operand.empty();
}

bool is_int(const any & operand)
{
    return operand.type() == typeid(int);
}

bool is_char_ptr(const any & operand)
{
    try
    {
        any_cast<const char *>(operand);
        return true;
    }
    catch(const std::tr2::bad_any_cast &)
    {
        return false;
    }
}

bool is_string(const any & operand)
{
    return any_cast<std::string>(&operand);
}

void count_all(many & values, std::ostream & out)
{
    out << "#empty == "
        << std::count_if(values.begin(), values.end(), is_empty) << std::endl;
    out << "#int == "
        << std::count_if(values.begin(), values.end(), is_int) << std::endl;
    out << "#const char * == "
        << std::count_if(values.begin(), values.end(), is_char_ptr) << std::endl;
    out << "#string == "
        << std::count_if(values.begin(), values.end(), is_string) << std::endl;
}

The following type, patterned after the OMG's Property Service, defines name-value pairs for arbitrary value types:

struct property
{
    property();
    property(const std::string &, const any &);

    std::string name;
    any value;
};

typedef std::list<property> properties;

The following base class demonstrates one approach to runtime polymorphism based callbacks that also require arbitrary argument types. The absence of virtual member templates requires that different solutions have different trade-offs in terms of efficiency, safety, and generality. Using a checked variant type offers one approach:

class consumer
{
public:
    virtual void notify(const any &) = 0;
    ...
};

Proposed Text

This clause describes components that C++ programs may use to perform operations on objects of a discriminated type.

[Note: The discriminated type may contain values of different types but does not attempt conversion between them, i.e. 5 is held strictly as an int and is not implicitly convertible either to "5" or to 5.0. This indifference to interpretation but awareness of type effectively allows safe, generic containers of single values, with no scope for surprises from ambiguous conversions. -- end note.]

ValueType requirements

A ValueType type shall meet the requirements for CopyConstructible [20.1.3]. A ValueType type may optiionally meet the requirements for Assignable [23.1]. The strong exception-safety guarantee is required for all forms of assignment. The destructor for ValueType types shall provide the no-throw exception-safety guarantee.

[Note: Values are strongly informational objects for which identity is not significant, i.e. the focus is principally on their state content and any behavior organized around that. Another distinguishing feature of values is their granularity: normally fine-grained objects representing simple concepts in the system such as quantities.

As the emphasis of a value lies in its state not its identity, values can be copied and typically assigned one to another, requiring the explicit or implicit definition of a public copy constructor and public assignment operator. Values typically live within other scopes, i.e. within objects or blocks, rather than on the heap. Values are therefore normally passed around and manipulated directly as variables or through references, but not as pointers that emphasize identity and indirection. --end note]

Header <any.hpp> synopsis

class bad_any_cast : public std::bad_cast
{
public:
  virtual const char * what() const;
};

class any
{
public:
  // construct/copy/destruct
  any();
  any(const any &);

  template<typename ValueType> any(const ValueType &);

  any & operator=(const any &);

  template<typename ValueType> any & operator=(const ValueType &);

 ~any();

  // modifiers
  any & swap(any &);

  // observers
  bool empty() const;
  const std::type_info & type() const;
};

template<typename ValueType> ValueType any_cast(const any &);
template<typename ValueType> const ValueType * any_cast(const any *);
template<typename ValueType> ValueType * any_cast(any *);

Class bad_any_cast

Objects of type bad_any_cast are thrown by a failed any_cast.

Class any

Objects of class any can hold instances of any type that satisfies ValueType requirements.

construct/copy/destruct

any();

Postconditions: this->empty()

any(const any & other);

Effects: Copy constructor that copies content of other into new instance, so that any content is equivalent in both type and value to the content of other, or empty if other is empty.

Throws: May throw a bad_alloc exception or any exceptions arising from the copy constructor of the contained type.

template<typename ValueType> any(const ValueType & value);

Effects: Makes a copy of value, so that the initial content of the new instance is equivalent in both type and value to value.

Throws: bad_alloc or any exceptions arising from the copy constructor of the contained type.

any & operator=(const any & rhs);

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.

template<typename ValueType> any & operator=(const ValueType & rhs);

Effects: Makes a copy of rhs, discarding previous content, so that the new content of is equivalent in both type and value to rhs.

Throws: bad_alloc or any exceptions arising from the copy constructor of the contained type. Assignment satisfies the strong guarantee of exception safety.

~any();

Effects: Releases any and all resources used in management of instance.

Throws: Nothing.

any modifiers

any & swap(any & rhs);

Effects: Exchange of the contents of *this and rhs.

Returns: *this

Throws: Nothing.

any queries

bool empty() const;

Returns: true if instance is empty, otherwise false.

Throws: Does not throw.

const std::type_info & type() const;

Returns: the typeid of the contained value if instance is non-empty, otherwise typeid(void).

[Note: Useful for querying against types known either at compile time or only at runtime. --end note]

Non-member functions

template<typename ValueType> ValueType any_cast(const any & operand);

Returns: The value contained by operand.

Throws: bad_any_cast if unsuccessful.

[Note: A copy is returned because the C++ keyword casts return copies.--end note.]

template<typename ValueType> const ValueType * any_cast(const any * operand);
template<typename ValueType> ValueType * any_cast(any * operand);

Returns: A similarly qualified pointer to the value content if successful, otherwise null.


© Copyright 2001 Kevlin Henney
© Copyright 2006 Beman Dawes

Revised 2006-02-24