【问题标题】:How do I get the name of the type currently held by an `any`?如何获取“any”当前持有的类型的名称?
【发布时间】:2017-08-22 23:00:56
【问题描述】:

假设我有:

  1. boost::any
  2. 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&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt;

【讨论】:

    猜你喜欢
    • 2012-01-10
    • 1970-01-01
    • 2016-11-02
    • 2020-04-02
    • 2017-09-09
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    相关资源
    最近更新 更多