Doing a static_assert that a template type is another template

后端 未结 3 2148
臣服心动
臣服心动 2020-11-29 04:51

How do I static_assert like this? Maybe Boost supports it if not C++ or new features in C++11?

template
struct foo {};

template

        
3条回答
  •  既然无缘
    2020-11-29 05:32

    You could do something along these lines. Given a trait that can verify whether a class is an instantiation of a class template:

    #include 
    
    template class TT>
    struct is_instantiation_of : std::false_type { };
    
    template class TT>
    struct is_instantiation_of, TT> : std::true_type { };
    

    Use it as follows in your program:

    template
    struct foo {};
    
    template
    struct bar {
      static_assert(is_instantiation_of::value, "failure");
    };
    
    int main()
    {
        bar b; // ERROR!
        bar> b; // OK!
    }
    

    If you want, you could generalize this to detect whether a class is an instance of a template with any number of (type) parameters, like so:

    #include 
    
    template class TT, typename T>
    struct is_instantiation_of : std::false_type { };
    
    template class TT, typename... Ts>
    struct is_instantiation_of> : std::true_type { };
    
    template
    struct bar {
      static_assert(is_instantiation_of::value, "failure");
    };
    

    You would then use it this way in your program:

    template
    struct bar {
      static_assert(is_instantiation_of::value, "failure");
    };
    
    int main()
    {
        bar b; // ERROR!
        bar> b; // OK!
    }
    

    Here is a live example.

提交回复
热议问题