Force Boost TypeIndex to report a specific pretty_name
Asked Answered
D

1

10

I want to specify that a certain type reported by Boost TypeIndex boost::typeindex::type_id<T>().pretty_name() would yield a specific name.

The problem I want to solve is that, as reported in other places, there is a particular case that is confusing, that is the std::string type (or alias) gets reported as std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >.

(I understand the reason for this, std::string is an alias. I just want to override the reported string in this particular case.)

I followed the instructions here http://www.boost.org/doc/libs/1_59_0/doc/html/boost_typeindex/making_a_custom_type_index.html and the beginning of the custom code looks like this:

namespace my_namespace { namespace detail {
    template <class T> struct typenum;
    template <> struct typenum<void>{       enum {value = 0}; };
    template <> struct typenum<std::string>{       enum {value = 1}; };

    struct my_typeinfo {const char* const type_;};

    const my_typeinfo infos[2] = {
        {"void"}, {"std::string"}
    };
    ...
    ... 

But at the end, the most I can do is to replace one type reporting by another, instead of just amending one case.

One light weight solution could be to specialize boost::typeindex::stl_type_index (the output type of type_id<std::string>()) but by then the actual static information of the class is lost. (there is no class to specialize.)

But this cannot be done without a full specialization of typeid<std::string> which seems to difficult to do.

Is there a workaround for this? I would prefer a solution within Boost.Typeindex rather than runtime string replacement.

Destructor answered 5/3, 2017 at 17:13 Comment(0)
D
0

This is a very dirty way I found but it is not perfect and can create other problems down the road.

struct std_string{}; // dummy replacement class name

namespace boost{
namespace typeindex{
    template<> boost::typeindex::stl_type_index type_id<std::string>() noexcept{
        return type_id<std_string>(); // will report "std_string", ugly, but better than `std::__cxx11::basic_string<...>`
    }
}}
Destructor answered 13/7, 2020 at 4:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.