确定 C++ 中的类型是否为同一基础类型的别名
我想编写一个模板化函数,它根据传入的模板类类型来更改其行为。为此,我想确定传入的类型。例如,这样的事情:
template <class T>
void foo() {
if (T == int) { // Sadly, this sort of comparison doesn't work
printf("Template parameter was int\n");
} else if (T == char) {
printf("Template parameter was char\n");
}
}
这可能吗?
I'd like to write a templated function which changes its behavior depending on template class types passed in. To do this, I'd like to determine the type passed in. For example, something like this:
template <class T>
void foo() {
if (T == int) { // Sadly, this sort of comparison doesn't work
printf("Template parameter was int\n");
} else if (T == char) {
printf("Template parameter was char\n");
}
}
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这就是模板专业化的目的,搜索该术语会给出大量示例。
This is the purpose of template specialization, a search for that term gives tons of examples.
通过使用部分专业化的力量,这可以在编译时完成:
在我的脑海中编译,但仍然应该工作。
By using the power of partial specialization, this can be done at compile time:
Compiled in my head, but should work nonetheless.
使用模板专业化或 typeid 可能适合您,尽管您可能更喜欢模板专业化,因为它不会产生 typeid 的运行时成本。例如:
Using template specialization or typeid would probably work for you, although you might prefer template specialization as it won't incur the runtime cost of typeid. For example:
直接使用 type_info ,或者更好的是 typeid 运算符来做到这一点。
Use type_info directly, or better still typeid operator to do that.