diff --git a/examples/user_defined_typeinfo.cpp b/examples/user_defined_typeinfo.cpp new file mode 100644 index 0000000..430a904 --- /dev/null +++ b/examples/user_defined_typeinfo.cpp @@ -0,0 +1,105 @@ +// Copyright 2013-2014 Antony Polukhin + +// Distributed under the Boost Software License, Version 1.0. +// (See the accompanying file LICENSE_1_0.txt +// or a copy at .) + +//[type_index_userdefined +/*` + The following example shows how a user defined type_info can be created and used. + Example works with and without RTTI. +*/ + +#include +#include +#include + +namespace my_namespace { + +class my_class; +struct my_struct; + +typedef std::vector my_classes; +typedef std::string my_string; + + +namespace detail { + template struct typenum; + template <> struct typenum{ enum {value = 0}; }; + template <> struct typenum{ enum {value = 1}; }; + template <> struct typenum{ enum {value = 2}; }; + template <> struct typenum{ enum {value = 3}; }; + template <> struct typenum{ enum {value = 4}; }; + + struct my_typeinfo { + char type_[2]; + }; + + template + inline const my_typeinfo& my_typeinfo_construct() { + static const my_typeinfo ret = {{ static_cast(typenum::value), '\0' }}; + return ret; + } +} + +class my_type_index: public boost::typeind::type_index_facade { + const detail::my_typeinfo* data_; + +public: + typedef detail::my_typeinfo type_info_t; + + inline my_type_index() BOOST_NOEXCEPT + : data_(&detail::my_typeinfo_construct()) + {} + + inline my_type_index(const type_info_t& data) BOOST_NOEXCEPT + : data_(&data) + {} + + inline const type_info_t& type_info() const BOOST_NOEXCEPT { + return *data_; + } + + inline const char* raw_name() const BOOST_NOEXCEPT { + return data_->type_; + } + + inline std::string pretty_name() const { + // Must be in sync with detail::typenum::value + static const char* names[] = { + "void", "my_class", "my_struct", "my_classes", "my_string" + }; + + const std::size_t indx = static_cast(data_->type_[0]); + return names[indx]; + } + + template + inline static my_type_index type_id() BOOST_NOEXCEPT { + return detail::my_typeinfo_construct(); + } +}; + +class my_class{}; +struct my_struct{}; + +} // namespace my_namespace + +using namespace my_namespace; +#include + +int main() { + my_type_index + cl1 = my_type_index::type_id(), + st1 = my_type_index::type_id(), + st2 = my_type_index::type_id(), + vec = my_type_index::type_id() + ; + + assert(cl1 != st1); + assert(st2 == st1); + assert(vec.pretty_name() == "my_classes"); + assert(cl1.pretty_name() == "my_class"); +} + +//] [/type_index_userdefined]