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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13636540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:34:09  来源:igfitidea点击:

How to check for the type of a template parameter?

c++templates

提问by WhatABeautifulWorld

Suppose I have a template function and two classes

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

class animal {
}
class person {
}

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

How do I do the check for T is animal? I don't want to have something that checks during the run time. Thanks

我如何检查 T 是动物?我不想在运行时进行检查。谢谢

回答by Kerrek SB

Use is_same:

使用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.

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

回答by Константин Гудков

I think todays, it is better to use, but only with C++17.

我认为今天,最好使用,但仅限于 C++17。

#include <type_traits>

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

If you use some type specific operations in if expression body without constexpr, this code will not compile.

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

回答by Edwin Pratt

In C++17, we can use variants.

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

To use std::variant, you need to include the header:

要使用std::variant,您需要包含标题:

#include <variant>

After that, you may add std::variantin your code like this:

之后,您可以std::variant像这样添加代码:

using Type = std::variant<Animal, Person>;

template <class T>
void foo(Type type) {
    if (std::is_same_v<type, Animal>) {
        // Do stuff...
    } else {
        // Do stuff...
    }
}

回答by template boy

You can specialize your templates based on what's passed into their parameters like this:

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

template <> void foo<animal> {

}

Note that this creates an entirely new function based on the type that's passed as T. This is usually preferable as it reduces clutter and is essentially the reason we have templates in the first place.

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