【问题标题】:Template meta programming : print type list [duplicate]模板元编程:打印类型列表
【发布时间】:2015-08-30 18:56:50
【问题描述】:

如何打印类型列表??

这是我尝试过的 + 我的类型列表:

template<typename ...T>
struct typeList;
template<typename H, typename ...T>
struct typeList<H, T...> {
    using head = H;
    using tail = typeList<T...>;
public:
    static inline void print(){
        std::cout << H::name << " "; // How can I get the name of H ???
        typeList<T...>::print();
    }
};

template<>
struct typeList<>{
   static inline void print(){
       std::cout << endl;
   }
};

这样typeList&lt;A,B,C,int&gt;::print() 会给出A b C int

A B 和 C 是一些用户定义的结构

我可以不在每个结构中添加名为name 的静态函数来执行此操作吗? 没有返回类型名称的编译时函数?

编辑:

这不是this 的重复,我在哪里提到了变量??

【问题讨论】:

标签: c++ templates


【解决方案1】:

您可以为此使用typeid(H).name()。不幸的是,name() 的格式是实现定义的,因此您不能依赖于在所有情况下获得您期望的输出。

例如,在 GCC 4.9.2 中,typeList&lt;A,B,C,int&gt;::print() 打印:

1A 1B 1C i

一个可能的解决方案是定义一个 getTypeName 模板函数,您可以专门针对不同的类型,然后在您没有专门化时使用 typeid().name()

template <typename T>
std::string getTypeName()
{
    return typeid(T).name();
}

template <>
std::string getTypeName<int>()
{
    return "int";
}

template <>
std::string getTypeName<A>()
{
    return "A";
}

这会打印出来:

A 1B 1C int

然后您可以轻松地为您的其他类型添加专业化。

【讨论】:

    猜你喜欢
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多