如何检查模板参数的类型? [英] How to check for the type of a template parameter?
本文介绍了如何检查模板参数的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个模板函数和两个类
Suppose I have a template function and two classes
class animal {
}
class person {
}
template<class T>
void foo() {
if (T is animal) {
kill();
}
}
如何检查T是动物?我不想有
在运行时检查的东西。感谢
How do I do the check for T is animal? I don't want to have something that checks during the run time. Thanks
推荐答案
使用 is_same
:
#include <type_traits>
template <typename T>
void foo()
{
if (std::is_same<T, animal>::value) { /* ... */ } // optimizable...
}
通常,这是一个完全不可行的设计, :
Usually, that's a totally unworkable design, though, and you really want to specialize:
template <typename T> void foo() { /* generic implementation */ }
template <> void foo<animal>() { /* specific for T = animal */ }
使用显式(非推导)参数的函数模板是不寻常的。这是不是没有闻到,但通常有更好的方法。
Note also that it's unusual to have function templates with explicit (non-deduced) arguments. It's not unheard of, but often there are better approaches.
这篇关于如何检查模板参数的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文