c++ compile-time check function arguments

前端 未结 4 480
情书的邮戳
情书的邮戳 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 01:03

    You may add a method like this:

    template 
    Matrix CreateMatrix()
    {
        static_assert(WIDTH > 0, "WIDTH > 0 failed");
        static_assert(HEIGHT > 0, "HEIGHT > 0 failed");
    
        return Matrix(WIDTH, HEIGHT);
    }
    
    int main() {
        Matrix m(0, 2);     // no static check
        Matrix m2 = CreateMatrix<0,2>(); // static check
    
        return 0;
    }
    

提交回复
热议问题