How to tell if template type is an instance of a template class?

前端 未结 3 1465
南旧
南旧 2021-01-19 02:41

I have a function that takes a template type to determine a return value. Is there any way to tell at compile time if the template type is some instantiation of a template c

3条回答
  •  被撕碎了的回忆
    2021-01-19 03:16

    Here's an option:

    #include 
    #include 
    #include 
    
    template  class>
    struct is_instance : public std::false_type {};
    
    template  class U>
    struct is_instance, U> : public std::true_type {};
    
    template 
    class Second 
    {};
    
    int main()
    {
        using A = Second;
        using B = Second;
        using C = float;
        std::cout << is_instance{} << '\n'; // prints 1
        std::cout << is_instance{} << '\n'; // prints 1
        std::cout << is_instance{} << '\n'; // prints 0
    }
    

    It's basically specializing the is_instance struct for types that are instantiations of a template.

提交回复
热议问题