Class template for numeric types

前端 未结 2 710

How do I write a class template that accepts only numeric types (int, double, float, etc.) as template?

2条回答
  •  醉酒成梦
    2020-12-08 07:30

    I found the error messages received from the template approach highly cryptic (VS 2015), but found that a static_assert with the same type trait also works and lets me specify an error message:

    #include 
    
    template 
    struct S
    {
        static_assert(std::is_arithmetic::value, "NumericType must be numeric");
    };
    
    template 
    NumericType add_one(NumericType n)
    {
        static_assert(std::is_arithmetic::value, "NumericType must be numeric");
        return n + 1;
    }
    
    int main()
    {
        S i;
        S s; //doesn't compile
    
        add_one(1.f);
        add_one("hi there"); //doesn't compile
    }
    

提交回复
热议问题