Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

c++ - find out the type of auto

I am playing with generic lambda in C++1y and I often confused by don't know what is the type of auto variable/parameter. Is any good way to find it out?

Currently I am using typeid(decltype(arg)).name()) but it is not very useful. @encode gives a slightly better result but still hard to decipher it

example:

auto f = [](auto && a, auto b) {
    std::cout << std::endl;
    std::cout << typeid(decltype(a)).name() << std::endl << @encode(decltype(a)) << std::endl;
    std::cout << typeid(decltype(b)).name() << std::endl << @encode(decltype(b)) << std::endl;
};

int i = 1;
f(i, i);
f(1, 1);
f(std::make_unique<int>(2), std::make_unique<int>(2));
auto const ptr = std::make_unique<int>();
f(ptr, nullptr);

output

i  // it does not tell me it is reference
^i // ^ means pointer, but it is actually reference, kinda pointer though
i
i

i
^i
i
i

NSt3__110unique_ptrIiNS_14default_deleteIiEEEE
^{unique_ptr<int, std::__1::default_delete<int> >={__compressed_pair<int *, std::__1::default_delete<int> >=^i}}
NSt3__110unique_ptrIiNS_14default_deleteIiEEEE
{unique_ptr<int, std::__1::default_delete<int> >={__compressed_pair<int *, std::__1::default_delete<int> >=^i}}

NSt3__110unique_ptrIiNS_14default_deleteIiEEEE
r^{unique_ptr<int, std::__1::default_delete<int> >={__compressed_pair<int *, std::__1::default_delete<int> >=^i}}
Dn
*

I mainly want is to know that is the parameter a lvalue ref/rvalue ref/passed by value etc.

and I am using Xcode 5.1.1

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use GCC’s __cxa_demangle function:

std::string demangled(std::string const& sym) {
    std::unique_ptr<char, void(*)(void*)>
        name{abi::__cxa_demangle(sym.c_str(), nullptr, nullptr, nullptr), std::free};
    return {name.get()};
}

auto f = [](auto && a, auto b) {
    std::cout << demangled(typeid(decltype(a)).name()) << '
';
    std::cout << demangled(typeid(decltype(b)).name()) << '
';
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...