简体   繁体   中英

C99 style variable-length array function signature in C++

In C99 we can write function signatures like so:

void func(int dim1, int dim2, float A[dim1 * dim2]);

dim1 and dim2 are runtime parameters. This is kind of nice, since any user of such a function immediately has an idea about the dimensionality of A and can thus infer further information without reading comments/documentation. This is especially true if dim1 and dim2 are parameters with semantics beyond what is shown here.

Is it possible to write an interface in C++ that gives a hint about the dimensionality and size of a vector/tensor that a function expects? Dimensionality can probably be encoded as a template argument (something I don't like in particular but that is another topic) but size? Any ideas?

Update:

I have to make it clearer, I guess. A C++ function would look like so:

void func(int dim1, int dim2, std::vector<float> A);

and one of the two dimensions can even be omitted (since it it is A.size()/dim ). But the signature does not tell the user anything about the size of the vector that the function expects. Of course I can assert(A.size() == dim1*dim2); and things like that. That is not what I am asking about. I'm asking how to make the interface more informative.

Update 2:

So I'm pretty sure what I want is this:

typedef int dim1; 
typedef int dim2; 
void func(Matrix<dim1, dim2> A);

As was mentioned in the answer, the information must be in the type - of course.

In C++, you'd do void func(Matrix const& A) . The dimensions would be encoded in the matrix itself, so there'd be no need to pass them separately. This both ensures the accuracy of the dimensions, and simplifies the calling idiom.

你可以使用std::array

void func(std::array<int, /* dimension */> &arr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM