我想知道是否有任何方法可以区分以下代码中显示的函数调用(以数组为参数):
#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“函数族”能够区分临时对象和命名对象。不是 foo_array 的情况。
在 C++11 中可以吗? 如果没有,你认为可能吗? (显然改变了标准)
问候。 费尔南多。
最佳答案
foo_array
没有问题。糟糕的是测试用例:"hello"
是一个左值!想想看。它不是临时的:字符串文字具有静态存储持续时间。
数组右值应该是这样的:
template <typename T>
using alias = T;
// you need this thing because char[23]{} is not valid...
foo_array(alias<char[23]> {});
关于c++ - 数组和右值(作为参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10624636/