Template which prints the name of the given type

丶灬走出姿态 提交于 2019-12-01 20:53:44

The only C++ language construct that can tell the difference between an lvalue that is an id-expression and an lvalue that is a reference is decltype. Here's an example of how to use it, including (ab)use of a macro to keep the same calling pattern you already have:

template <typename T> std::string TypeName() {
    auto name = typeid(T()).name();  // function type, not a constructor call!
    int status = 0;

    std::unique_ptr<char, void(*)(void*)> res {
        abi::__cxa_demangle(name, NULL, NULL, &status),
        std::free
    };

    std::string ret((status == 0) ? res.get() : name);
    if (ret.substr(ret.size() - 3) == " ()") ret.resize(ret.size() - 3);
    return ret;
}
#define TypeName(e) TypeName<decltype(e)>()

Because abi::__cxa_demangle ignores top-level cv and reference qualifiers, we construct a function type and then strip the trailing brackets.

This gives int const, int&, int const& as required.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!