我正在使用 C++1y 中的通用 lambda,我经常因不知道 auto
变量/参数的类型而感到困惑。有什么好的方法可以查出来吗?
目前我正在使用 typeid(decltype(arg)).name())
但它不是很有用。 @encode给出了稍微好一点的结果,但仍然难以破译它
例子:
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);
输出
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
*
我主要想知道参数是左值引用/右值引用/按值传递等。
我正在使用 Xcode 5.1.1
最佳答案
使用 GCC 的 __cxa_demangle
功能:
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()) << '\n';
std::cout << demangled(typeid(decltype(b)).name()) << '\n';
};
关于c++ - 找出汽车的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23266391/