How to check for the type of a template parameter?

前端 未结 4 1946
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 04:11

Suppose I have a template function and two classes

class animal {
}
class person {
}

template
void foo() {
  if (T is animal) {
    kill();
          


        
4条回答
  •  佛祖请我去吃肉
    2020-11-28 04:22

    In C++17, we can use variants.

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

    #include 
    

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

    using Type = std::variant;
    
    template 
    void foo(Type type) {
        if (std::is_same_v) {
            // Do stuff...
        } else {
            // Do stuff...
        }
    }
    

提交回复
热议问题