使用Array模板参数一回 [英] Using the Array Template Parameter for a Return
问题描述
(我似乎无法为这种模式找到一个名字,但如果你能,你会得到奖金给予好评!)这个模板范例用于prevent从衰变成一个指针数组:
(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]);
我们能够在富
正文中使用 N
获得大小关栏
。鉴于为const char []数组=Lorem存有
我们使用这个调用富(阵列)
来定义栏
为为const char(安培)。[12]
,有效地传递2个参数为一价
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]);
,这样我就可以通过此阵,并有另一个引用,如:自动结果= foo的(巴)
在code我这里得到的错误:
The code I have here yields the error:
面目全非模板声明/定义
unrecognizable template declaration/definition
这可能吗?
编辑:
有关澄清,我希望能够有一个函数返回,这将导致在相当于:
For clarification, I want to be able to have a function return that will result in the equivalent of:
auto& result = bar;
这样结果
将是为const char(安培)[*]
,其中 *
是栏
。
推荐答案
C ++语法是美妙的:
C++ syntax is wonderful:
template <std::size_t N>
const char (&f(const char (&arr)[N]))[N] // take that, Lisp
{
return arr;
}
对于不太自虐:
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).
这篇关于使用Array模板参数一回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!