数组和Rvalues(作为参数)

时间:2012-05-16 18:40:19

标签: c++ arrays c++11 rvalue-reference rvalue

我想知道是否有任何方法可以区分以下代码中显示的函数调用(使用数组作为参数):

#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“function family”能够区分临时对象和命名对象。不是foo_array的情况。

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

的问候。 费尔南多。

1 个答案:

答案 0 :(得分:15)

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

数组rvalue将是这样的:

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

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