如何检查模板参数的类型?

时间:2012-11-29 23:15:06

标签: c++ templates

假设我有一个模板函数和两个类

class animal {
}
class person {
}

template<class T>
void foo() {
  if (T is animal) {
    kill();
  }
}

我如何检查T是动物?我不想要 在运行时检查的东西。感谢

5 个答案:

答案 0 :(得分:79)

使用is_same

#include <type_traits>

template <typename T>
void foo()
{
    if (std::is_same<T, animal>::value) { /* ... */ }  // optimizable...
}

通常,这是一个完全不可行的设计,你真的想专门化

template <typename T> void foo() { /* generic implementation  */ }

template <> void foo<animal>()   { /* specific for T = animal */ }

另请注意,具有显式(非推断)参数的函数模板是不常见的。这并不是闻所未闻,但往往有更好的方法。

答案 1 :(得分:14)

我认为今天最好使用,但只能使用C ++ 17。

#include <type_traits>

template <typename T>
void foo() {
    if constexpr (std::is_same_v<T, animal>) {
        // use type specific operations... 
    } 
}

如果在没有constexpr的if表达式主体中使用某些特定于类型的操作,则此代码将无法编译。

答案 2 :(得分:6)

在C ++ 17中,我们可以使用 变体

要使用(0..<projectsList.size()).each { i -> branches["Build ${projectsList[i]}"] = { buildProject(i) } } ,您需要包括标题:

std::variant

之后,您可以像这样在代码中添加#include <variant>

std::variant

答案 3 :(得分:5)

您可以根据传递给参数的内容来专门化模板,如下所示:

template <> void foo<animal> {

}

请注意,这会根据作为T传递的类型创建一个全新的函数。这通常是优选的,因为它减少了混乱,并且基本上是我们首先拥有模板的原因。

答案 4 :(得分:1)

parameters 仅在 C++11 之后可用。对于 C++11 之前的版本,您可以使用 std::is_same():

typeid()
相关问题