Enforce template type through static_assert

前端 未结 3 685
梦如初夏
梦如初夏 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: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 
    struct CheckTypes
    {
        static const bool value = false;
    };
    
    template 
    struct CheckTypes
    {
        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::value, "Error!");
    

提交回复
热议问题