如何在编译时漂亮地打印模板参数的名称
How to pretty print the name of a template parameter at compile time
问题很简单:如何在C++类中漂亮地打印模板参数的名称,并在编译时将其分配给类变量?似乎typeinfo
(typeid
)和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还可以用于(和扩展)其他目的。
相关文章:
- C++ cout 不打印所有参数
- 在 masm x64 上打印具有多个参数
- 打印带有指针的参数和环境
- 在C++中使用getopt时打印默认参数
- 使用宏定义打印格式参数
- 为什么我不能提供一个字符串参数来打印 ncurses?
- 作为参数传递的打印功能指针导致屏幕上打印"1"
- 如何打印作为参数传递的函数的名称
- 如何使用递归按从 1 到 n 的升序打印数字,其中 n 在该函数的参数中给出
- 如果我不打印函数参数的值,则将其转换为等于零
- 为什么我的代码两次打印相同的命令行参数
- C++ 命令行参数不从文本文件中打印出值
- 我需要创建一个函数在用户下打印"=",但由于变量是使用 main() 声明的,因此函数看不到参数
- GDB有没有办法在不省略模板参数的情况下打印类型
- 如何打印带有参数的变量的名称
- 如何对函数参数的类型铸件进行G 打印警告
- 如何在编译时漂亮地打印模板参数的名称
- 如何使用可变模板打印出函数的参数
- 如何使用带2个参数的void函数多次打印消息
- 将 char* 字符串参数打印到 UnicodeString 对象中