Reputation: 38919
(I can't seem to find a name for this paradigm, but you'll get a bonus upvote if you can!) This template paradigm is used to prevent an array from decaying into a pointer:
template <size_t N>
void foo(const char (&bar) [N]);
We are able to use N
in the body of foo
to get the size off bar
. Given const char array[] = "lorem ipsum"
we use this call foo(array)
to define bar
as a const char (&) [12]
, effectively passing 2 parameters for the price of one.
I want to use this same idea but in a return, for example:
template <size_t N>
const char (&) [N] foo(const char (&bar) [N]);
Such that I could pass the array through, and have another reference to it, such as: auto result = foo(bar)
The code I have here yields the error:
unrecognizable template declaration/definition
Is this possible?
EDIT:
For clarification, I want to be able to have a function return that will result in the equivalent of:
auto& result = bar;
Such that result
will be a const char (&) [*]
where *
is the size of bar
.
Upvotes: 0
Views: 59
Reputation: 477110
C++ syntax is wonderful:
template <std::size_t N>
const char (&f(const char (&arr)[N]))[N] // take that, Lisp
{
return arr;
}
For the less masochistic:
template <std::size_t N> using CarrN = const char[N];
template <std::size_t N>
CarrN<N> & f(CarrN<N> & arr)
{
return arr;
}
As for terminology: We usually say that "arr
is passed by reference", though the more discerning user might say "passed as an lvalue" (and also returned as such).
Upvotes: 4