【问题标题】:How do I get the name of the type currently held by an `any`?如何获取“any”当前持有的类型的名称?
【发布时间】:2017-08-22 23:00:56
【问题描述】:
假设我有:
-
boost::any 或
-
std::any(我使用的是 C++17)
我不知道的类型。我是否可以打印或作为字符串获取 any 所持有的类型的名称?
注意:即使是一个错位的类型名称——你用typeid(TR).name() 得到的那种——就足够了,我可以使用abi::__cxa_demangle 从那里得到它。
【问题讨论】:
标签:
c++
reflection
c++17
type-erasure
boost-any
【解决方案1】:
#include <any>
#include <iostream>
using namespace std;
namespace TestNamespace {
class Test {
int x{ 0 };
int y{ 1 };
};
}
int main()
{
any thing = TestNamespace::Test();
cout << thing.type().name() << endl;
cin.get();
return 0;
}
输出:
class TestNamespace::Test
哦,至少在 msvc 中,std 模板库类的 type_info 看起来比 std::string 丑得多(看起来像:class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)