如何在编译时漂亮地打印模板参数的名称

How to pretty print the name of a template parameter at compile time

本文关键字:参数 打印 编译 漂亮      更新时间:2023-10-16

问题很简单:如何在C++类中漂亮地打印模板参数的名称,并在编译时将其分配给类变量?似乎typeinfotypeid)和boost::typeindex都必须在运行时求值,或者至少作为它们的一部分求值。这显然不允许编译器完全解决包含对此函数之一的调用的constexpr

template<typename T>
class X
{
   public:
      static const char * name = /* SOME C++ code transforming T in a string (either std::string or char */
};

我错过了什么?是否只能在运行时生成名称?在这种情况下,我真的需要一个实例化的对象吗?在我看来,这似乎不对,因为以下内容在没有任何实例的情况下都能完美工作:

#include <iostream>
#include <string>
#include <boost/type_index.hpp>
using namespace std;
template<class T>
class X
{
        public:
                static std::string name()
                {
                        return boost::typeindex::type_id<T>().pretty_name();
                }
};
struct foobar {};
int main()
{
        cout << X<int>::name() << endl;
        cout << X<foobar>::name()<< endl;
}

因此,我不希望将name()作为类方法,而希望将其作为类变量。

我认为,使用自定义类型特征是可能的。请参阅下一个示例:

#include <iostream>
#include <string>
using namespace std;
//Using stub type traits
template <class T>
struct TypeTraits;
//your TypeTraits for specific types...
template<>
struct TypeTraits<int>
{
    constexpr static const char *name = "int";
};
template<class T>
class X
{
    public:
            constexpr static const char * name = TypeTraits<T>::name;
};
struct foobar {};
//TypeTraits for custom  foobar
template<>
struct TypeTraits<foobar>
{
    constexpr static const char *name = "foobar";
};

int main()
{
    //Now you can use static member here
    cout << X<int>::name << endl;
    cout << X<foobar>::name<< endl;
}

此外,TypeTraits还可以用于(和扩展)其他目的。