名稱空間
變體
操作

std::type_info::name

來自 cppreference.com
< cpp‎ | 型別‎ | 型別資訊
 
 
 
 
 
const char* name() const;
(C++11 起無異常丟擲)

返回一個實現定義的以 null 結尾的字元字串,其中包含型別的名稱。不作任何保證;特別是,對於幾種型別,返回的字串可能相同,並且在同一程式的多次呼叫之間可能會更改。

目錄

[編輯] 引數

(無)

[編輯] 返回值

以 null 結尾的字元字串,包含型別的名稱。

[編輯] 注意

返回指標所指向的陣列的生命週期未指定,但實際上它會持續存在,只要給定型別的 RTTI 資料結構存在,該資料結構具有應用程式生命週期,除非從動態庫(可解除安裝)載入。

一些實現(例如 MSVC、IBM、Oracle)生成人類可讀的型別名稱。其他實現,最著名的是 gcc 和 clang,返回由 Itanium C++ ABI 指定的混淆名稱。混淆名稱可以使用實現特定的 API(例如 abi::__cxa_demangle)直接或透過 boost::core::demangle 轉換為人類可讀的形式。它也可以透過命令列實用程式 c++filt -t 進行管道傳輸。

[編輯] 示例

#include <boost/core/demangle.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include <typeinfo>
 
struct Base { virtual ~Base() = default; };
struct Derived : Base {};
 
int main()
{
    Base b1;
    Derived d1;
 
    const Base* pb = &b1;
    std::cout << typeid(*pb).name() << '\n';
    pb = &d1;
    std::cout << typeid(*pb).name() << '\n';
 
    std::string real_name = boost::core::demangle(typeid(pb).name());
    std::cout << typeid(pb).name() << " => " << real_name << '\n';
 
    std::cout << "c++filt => " << std::flush;
    std::string s = typeid(pb).name();
    std::system(("c++filt -t " + s).data());
}

可能的輸出

// GCC/Clang:
4Base
7Derived
PK4Base => Base const*
c++filt => Base const*
 
// MSVC:
struct Base
struct Derived
struct Base const * __ptr64 => struct Base const * __ptr64

[編輯] 參閱

(C++11)
返回對於相同型別相同的雜湊值
(public member function) [編輯]