Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing a C-array into a function 'on the fly', without defining a variable

There exist many similar questions for C, e.g. this one, but i’m searching for the simplest and most readable way in C++ to pass an C-array into a function without first defining a variable for it.

Given a
void f(double const* a)
these are not possible (but the first one is in C99):

f((double *[]){1,2});
f({1,2});

Of course defining a variable first is always possible, but that’s not what i’m looking for:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

double a[] = { 1.2, 3.4 };
f(a);

However, it is possible to wrap things into a struct, f.e. like

struct A { double a[2]; };
f(A{2.3,4.5}.a);

and that type can be reused, so that’s already a little win

Live Demo

but this still feels clumsy.

Is there a simpler and more readable way? In one of the current standards or maybe an upcoming one?

EDIT: Sorry, i didn’t mention that before; i can’t change the target api. A pointer to a double is expected.

>Solution :

This function is great for that:

template<typename T, std::size_t N>
constexpr T* temporary_array(T(&& arr)[N]) noexcept { return arr; }

Then you can simply call f(temporary_array<double>({1,2})); (or f(temporary_array({1., 2.}))).

In C++20, you can write f(std::type_identity_t<double(&&)[]>{1,2}). f(std::type_identity<double[]>{1, 2}) should also work in any C++ version, but GCC has a long-standing bug that doesn’t allow this to compile.

Looking for standard library solutions, your struct A can be replaced with std::array<double, 2>. Writing out the size parameter is annoying, but it can be replaced with CTAD:

f(std::array{ 1., 2. }.data());
f(std::array<double, 2>{1, 2}.data());
// (These will call move constructors)
f(std::to_array<double>({1, 2}).data());
f(std::to_array({1., 2.}).data());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading