Enforce template type through static_assert

前端 未结 3 691
梦如初夏
梦如初夏 2021-02-12 14:40

I\'m trying to understand the usefulness of static_assert, and I want to know if it can help me in enforcing a design, and if so, how.

I have a general temp

相关标签:
3条回答
  • 2021-02-12 15:21

    http://en.cppreference.com/w/cpp/header/type_traits

    std::is_base_of and std::is_convertible could help with your first issue and as for the second,

    static_assert(!std::is_same<float,T>(),"type can't be float");

    hopefully this helps someone else who stumbles upon this question, assuming OP probably found an answer in the 4 years since it was asked :)

    0 讨论(0)
  • 2021-02-12 15:22

    If it can only work for a specialization of the template class, then have the default template class raise a static assert:

    template <class T, size_t S = sizeof(T)>
    struct Helper
    {
       static_assert(sizeof(T) == -1, "You have to have a specialization for Helper!" );
    }
    

    The default template class will only be chosen if there isn't a better specialization, therefore the assert will be risen.

    You can use the same technique to disallow types, but you'll need another template parameter that will be used for the static assert check.

    template <class T, class G = T, size_t S = sizeof(T)>
    struct Helper
    {
       static_assert(sizeof(G) == -1, "You have to have a specialization for Helper!" );
    }
    
    template <class G>
    struct Helper<float,G>
    {
       static_assert(sizeof(G) == -1, "You can't use float !" );
    }
    
    template <>
    struct Helper<int>
    {
     //This is a good specialization
    };
    

    Then you can try it with these variables:

    Helper<bool> a;  //"You have to have a specialization for Helper!"
    Helper<float> b; //"You can't use float !"
    Helper<int> c;   //compiles OK
    
    0 讨论(0)
  • 2021-02-12 15:44

    I figured out a better solution for this problem by combining the answers and comments here.

    I can define a static type checker like so:

    template <class A, class B>
    struct CheckTypes
    {
        static const bool value = false;
    };
    
    template <class A>
    struct CheckTypes<A, A>
    {
        static const bool value = true;
    };
    

    Not sure if such a struct already exists in the standard library. Anyways, then in Foo, I can check for types and sizes using:

    static_assert((sizeof(T) == sizeof(long) || sizeof(T) == sizeof(int)) && !CheckTypes<T, float>::value, "Error!");
    
    0 讨论(0)
提交回复
热议问题