将数组作为r-Value传递给函数争论 [英] Pass an array to a function arguement as r-Value

查看:88
本文介绍了将数组作为r-Value传递给函数争论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我的问题可能非常简单或无法解决。

假设我们定义了两个函数(尽可能简单),如下所示:



Hi there,
My Question may quite simple or unsolvable.
Say we define two function (as simple as possible) as below :

void foo(int&& arg){
 ...
}
 void bar(const int* x){
 ...
}





我们都知道我们可以简单调用bar函数只使用rvalue of int-



we all know we can simply call "bar" function just using rvalue of int-

foo(47);



但是当我们尝试使用数组的rvalue类型调用bar函数时会出现问题 -


but problem arise when we trying to invoke bar function using rvalue type of a array-

bar({1,2,3});



参数被编译器视为 std :: initilizer_list ,那么我们如何解决这个问题特别的问题?

由于某些运行时冲突,我们不能构造一个数组的r值吗?

请解释。

谢谢。


argument is treated as std::initilizer_list by compiler,so How can we solve this particular problem?
Can't we construct a r-value of a array due to some run-time conflicts?
Please explain.
Thank you.

推荐答案

可以通过访问类rvalues的数组成员或使用标识模板来构造数组rvalues:



Array rvalues can be constructed by accessing array members of a class rvalues or by using an identity template:

#include <iostream>

void f(int (&&x)[2][3]) { std::cout << sizeof x << '\n'; }

struct X { int i[2][3]; } x;
template<typename T> using identity = T;

int main()
{
    f(X().i); // binds to rvalue
    f(identity<int[][3]>{{1,2,3},{4,5,6}}); // binds to rvalue
}





为什么不接受初始化列表呢?



Why not just accept initializer lists though?


这篇关于将数组作为r-Value传递给函数争论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆