Incomprehensible function signature - Return reference to an array of N objects

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

I've come across the following signature

double(&rotate_vec(double(&val)[4]))[4]; 

In the comments it "claims" to accept and return an array of four elements. My first reaction was that this does not even look standard c++ yet this compiles:

double(&rotate_vec(double(&val)[4]))[4] {     // ...      return val; }  int main() {     double ar[4] = { 1, 2, 3, 5 };     rotate_vec(ar);     return 0; } 
  1. How is this c++ ? How would you read it ?
  2. We can't return an array from a function, just pointers, or can we ?

回答1:

With C++03 the best you can do to simplify the original

double(&rotate_vec(double(&val)[4]))[4]; 

is to use a typedef, to wit:

typedef double Four_vec[4]; Four_vec& rotate_vec( Four_vec& val ); 

In C++11 you can write

auto rotate_vec( double (&val)[4] )     -> double (&)[4]; 

although I'd use a typedef or C++11 using to clarify.


Regarding

“We can't return an array from a function, just pointers, or can we ?”

you can't return a raw array by value, but you can return a pointer or reference, or you can wrap it in a struct, like C++11 std::array.



回答2:

double ( &rotate_vec( double (&val)[4] ) )[4] 

A function named rotate_vec

double ( &rotate_vec( double (&val)[4] ) )[4] 

...that takes as an argument, a reference to an array of four doubles

double ( &rotate_vec( double (&val)[4] ) )[4] 

...and returns a reference to an array of four doubles.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!