首页 > 解决方案 > 如何打印类型名称(主题模板)

问题描述

嘿家伙这是我在文件 h 上的代码,我需要创建需要打印类型的方法。

    #include <iostream>
    #include <typeinfo>
    using namespace::std;

template <class T>
class Set {
    T* group;
    int size_group;
public:
    Set():group(NULL),size_group(0){};
    Set(T*,int);
    Set(const Set<T>&);
    ~Set();

    void PrintObj()const;
    bool isThere(const T&)const;
    void getType()const;

};


template <class T>
void Set<T>::getType() const{
    cout << "The type is: " << typeid(*this).name() << endl;
}

主要的:

#include "Set.h"

int main() {
    int arr[] = {1,4,5,6,3,2};
    int arr2[] = {5,2,6};

    Set<int> j(arr,(sizeof(arr)/sizeof(arr[0]))),l(arr2,sizeof(arr2)/sizeof(arr2[0])),k;

    j.getType();
}

输出

The type is: 3SetIiE

我如何打印类型名称?这对我来说有点胡言乱语

标签: c++templates

解决方案


你看到的是一个被破坏的名字。您可以使用boost::core::demangle它来对其进行分解(https://www.boost.org/doc/libs/1_73_0/libs/core/doc/html/core/demangle.html)。

std::cout << boost::core::demangle(typeid(*this).name()) << std::endl;

推荐阅读