数组和右值(作为参数)

编程入门 行业动态 更新时间:2024-10-16 00:18:46
本文介绍了数组和右值(作为参数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道是否有任何方法来区分函数调用(使用数组作为参数)如下代码所示:

I wonder if there is any way to differentiate the function calls (with arrays as parameters) shown in the following code:

#include <cstring> #include <iostream> template <size_t Size> void foo_array( const char (&data)[Size] ) { std::cout << "named\n"; } template <size_t Size> void foo_array( char (&&data)[Size] ) //rvalue of arrays? { std::cout << "temporary\n"; } struct A {}; void foo( const A& a ) { std::cout << "named\n"; } void foo( A&& a ) { std::cout << "temporary\n"; } int main( /* int argc, char* argv[] */ ) { A a; const A a2; foo(a); foo(A()); //Temporary -> OK! foo(a2); //------------------------------------------------------------ char arr[] = "hello"; const char arr2[] = "hello"; foo_array(arr); foo_array("hello"); //How I can differentiate this? foo_array(arr2); return 0; }

foofunction family能够区分临时对象。不是foo_array的情况。

The foo "function family" is able to distinguish a temporary object from a named. Is not the case of foo_array.

在C ++ 11中是否可能? 如果没有,你认为可能吗? (显然改变了标准)

Is it possible in C++11 ? If not, do you think could be possible? (obviously changing the standard)

问候。 Fernando

Regards. Fernando.

推荐答案

foo_array 。这是坏的测试用例:hello是一个左值!想想吧。这不是一个临时的:字符串文字有静态存储持续时间。

There is nothing wrong with foo_array. It's the test case that is bad: "hello" is an lvalue! Think about it. It is not a temporary: string literals have static storage duration.

数组右值将是这样:

template <typename T> using alias = T; // you need this thing because char[23]{} is not valid... foo_array(alias<char[23]> {});

更多推荐

数组和右值(作为参数)

本文发布于:2023-10-27 10:25:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533094.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!