C ++编译时检查函数参数 [英] 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?
如果值不是静态的:
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?
编辑:我认为可以使用 constexpr构造函数,但是无论如何,无论有没有constexpr,都不允许重载。因此,无法以我想的方式解决问题。
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.
推荐答案
要获取编译时错误,您需要一个模板:
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)
如果没有static_assert(在此我切换为无符号):
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> {};
此处不支持空矩阵(MatrixTemplate< 0,0>)。但是,调整static_asserts或MatrixTemplate< 0类应该是一项容易的任务。 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>.
这篇关于C ++编译时检查函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!