c++ compile-time check function arguments

前端 未结 4 481
情书的邮戳
情书的邮戳 2020-12-18 00:11

I\'m searching a way to check function arguments in compile-time if it\'s possible to do for compiler.

To be more specific: assume that we have some class Matrix.

4条回答
  •  轮回少年
    2020-12-18 00:47

    Run-time:

    Matrix(int width, int height):
        x_size{width},
        y_size{height}
    {
            assert(x_size>0);
            assert(y_size>0);
    }
    

    Compile-time (Actually you couldn't do it with function arguments. You can use template ways):

    template 
    class Matrix
    {
        const size_t x_size = WIDTH;
        const size_t y_size = HEIGHT;
    
        static_assert(WIDTH > 0, "Width must > 0");
        static_assert(HEIGHT > 0, "Height must > 0");
    };
    

提交回复
热议问题