我想知道是否有任何方法来区分函数调用(使用数组作为参数)如下代码所示:
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]> {});更多推荐
数组和右值(作为参数)
发布评论