Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

c++ compile-time check function arguments

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.

class Matrix
{
    int x_size;
    int y_size;

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

int main()
{
    Matrix a; // good.
    Matrix b(1, 10); // good.
    Matrix c(0, 4); // bad, I want compilation error here.
}

So, can I check or differentiate behavior (function overloading?) in case of static (source-encoded) values passed to function?

If value isn't static:

std::cin >> size;
Matrix d(size, size);

we're only able to do runtime checks. But if values are encoded in source? Can I make compile-time check in this case?

EDIT: I think this can be possible with constexpr constructor, but anyway overloading with and without constexpr isn't allowed. So problem can't be resolved in way I suppose.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To get a compile time error you would need a template:

template <int width, int height>
class MatrixTemplate : public Matrix
{
    static_assert(0 < width, "Invalid Width");
    static_assert(0 < height, "Invalid Height");
    public:
    MatrixTemplate()
    : Matrix(width, height)
    {}
};

(Btw.: I suggest unsigned types for indices)

If you do not have static_assert (here I switch to unsigned):

template <unsigned width, unsigned height>
class MatrixTemplate : public Matrix
{
    public:
    MatrixTemplate()
    : Matrix(width, height)
    {}
};

template <> class MatrixTemplate<0, 0> {};
template <unsigned height> class MatrixTemplate<0, height> {};   
template <unsigned width> class MatrixTemplate<width, 0> {};

There is no support for empty matrices (MatrixTemplate<0, 0>), here. But it should be an easy task to adjust the static_asserts or class MatrixTemplate<0. 0>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...