如何写一个C ++转换操作符来返回数组引用? [英] How to write a C++ conversion operator returning reference to array?
问题描述
在C ++中可以在类或结构中添加隐式转换操作符。例如,3D向量类型通常包括这样的:
In C++ one can add implicit-conversion operators in a class or struct. For instance, 3D vector types usually include something like:
struct Vector {
float x, y, z;
operator float * () { return reinterpret_cast<float *>(this); }
};
允许访问向量与标元素,传递给那些需要一个指针,等我突然想知道的功能:我们可以改为编写返回到浮动的数组引用的转换操作符,而不是一个指针浮?
to allow accessing the vector's elements with subscripts, passing to functions that want a pointer, etc. It occurred to me to wonder: can we instead write a conversion operator that returns a reference to array of float, instead of a pointer to float?
(这是纯粹的学术兴趣。我不知道有什么好处的引用到阵列会的,如果有的话,过一个简单的指针。)
(This is of purely academic interest. I don't know what benefits a reference-to-array would have, if any, over a simple pointer.)
作为一个自由的功能,我们可以做到这一点,如:
As a free function we can do this like:
float (&convert(Vector & v))[3]
{
return reinterpret_cast<float(&)[3]>(v);
}
Vector v;
convert(v);
不过,我一直没能找到合适的语法来做到这一点作为一个转换操作符。我试过喜欢的东西:
However, I haven't been able to find the right syntax to do this as a conversion operator. I've tried things like:
operator float(&)[3] ()
operator float(&())[3]
float (&operator())[3]
和其他各种排列,但我只是得到了各种各样的语法错误(G ++ 4.8.1)。
and various other permutations, but I just get various syntax errors (g++ 4.8.1).
是否可以写一个转换操作符返回数组的引用,如果是这样,什么是语法,这样做呢?
Is it possible to write a conversion operator returning a reference to array, and if so, what is the syntax to do so?
推荐答案
在事实上,你可以,你几乎是最后一个了吧:
In fact you can, you almost had it with the last one:
(&operator float())[3];
而对于一个typedef是否必要过这个问题,我认为这是从阅读 HTTP的评论:// stackoverflow.com/a/6755760/2925619 (这答案是什么帮助我得到的语法以上为好)。
As for the question of whether or not a typedef is ever necessary, I think it is from reading the comments on http://stackoverflow.com/a/6755760/2925619 (which answer is what helped me get the syntax for the above as well).
修改
显然,这语法不正确,返回数组的引用是被禁止的克里斯发现了我们。我猜你只需要解决一个的typedef
。
Apparently, this syntax is incorrect and returning a reference to an array is forbidden as chris discovered for us. I guess you'll just have to settle for a typedef
.
这篇关于如何写一个C ++转换操作符来返回数组引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!