Doing a static_assert that a template type is another template

后端 未结 3 2144
臣服心动
臣服心动 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:28

    Some small improvements over the other answers:

    • the name actually makes sense regarding the order of the parameters
    • handles const, volatile, and reference types properly via std::decay
    • implements C++14-style _v constexpr variable
    • accepts an arbitrary number of types to test against (tests for ALL)

    I have intentionally not put the std::decay_t on the is_template_for_v because a type trait should work identically regardless of whether it is called with the _v suffix or not.

    This does require C++17 for std::conjunction, but you can either remove the variadic feature or implement your own conjunction using c++11/14.

    template class tmpl, typename T>
    struct _is_template_for : public std::false_type {};
    
    template class tmpl, class... Args>
    struct _is_template_for> : public std::true_type {};
    
    template class tmpl, typename... Ts>
    using is_template_for = std::conjunction<_is_template_for>...>;
    
    template class tmpl, typename... Ts>
    constexpr bool is_template_for_v = is_template_for::value;
    

    Usage:

    static_assert(is_template_for_v>); // doesn't fire
    

提交回复
热议问题