C++模板T,检测Type为字符串形式
我有一个 C++ 模板函数,它基本上将值写入 XML 文件,出于验证目的,我希望写出变量类型及其值。我目前正在使用 typeid(T).name()
,它非常适合 int
、double
等,但我想要一个 的特殊情况>char
数组和 std::string
以便它总是写出“字符串”或比以下内容更有意义的内容:
class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
或者
char const [2]
关于如何以优雅的方式做到这一点有什么想法吗?
我的代码(删减)看起来像这样(不是函数只是模板)
template <typename T> bool SetValue(const std::string §ionName, const std::string &valueName, const T &value)
{
myXMl->AddAttribute(TYPE_DEF,typeid(T).name());
return true;
}
I have a template function in C++ that basically writes values to an XML file, for validation purposes I wish to write out the variable type as well as its value. I am currently using typeid(T).name()
which works great for int
, double
etc but I want a special case for char
arrays and std::string
so that it always writes out "string" or something more meaningful than:
class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
or
char const [2]
Any ideas on how I can do this in an elegant way?
My code (cut down) looks like this (not the function is template only)
template <typename T> bool SetValue(const std::string §ionName, const std::string &valueName, const T &value)
{
myXMl->AddAttribute(TYPE_DEF,typeid(T).name());
return true;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以为此使用特征类:
此模板实现默认情况。现在您可以将其专门用于应该具有特殊名称的类型:
您的代码将如下所示:
You can use a traits class for this:
This template implements the default-case. Now you can specialize it for types that should have special names:
Your code would then look like this:
您可以将您的类型包装在填充函数中。这些函数实际上不必定义,因为它们永远不会被执行;您只需要声明来采用重载决策来为您选择正确的函数,这样您就可以使用 typeid() 表达式获取其结果的类型。
请记住,模板函数仅选择完美匹配,而非模板函数的重载允许隐式转换。
例子:
You can wrap your type inside shim functions. These functions don't actually have to be defined, since they won't be ever executed; you only need declarations to employ overloading resolution to pick the right function for you, so you can take the type of its result with typeid() expression.
Remember that template functions are only selected for perfect match, whilst overloading of non-template functions allows for implicit conversions.
Example: