数组和右值(作为参数) [英] Arrays and Rvalues (as parameters)

查看:152
本文介绍了数组和右值(作为参数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有什么方法来区分函数调用(使用数组作为参数)在以下code所示:

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;
}

在富功能的家庭,是能够从一个名为区分临时对象。是不是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)

问候。
费尔南多。

Regards. Fernando.

推荐答案

有什么错 foo_array 。这是测试用例是坏的:你好是一个左值!想想吧。这不是一个暂时的:字符串具有静态存储持续时间

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.

这是数组右值将是这样的:

An array rvalue would be something like this:

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

foo_array(alias<char[23]> {});

这篇关于数组和右值(作为参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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