[英]C++11 std::copy inside functions
I am writing a new cross-platform toolbox and would like to be up-to-date with the C++11 extensions. 我正在编写一个新的跨平台工具箱,并希望了解最新的C ++ 11扩展。 I ran into a problem, where std::copy doesn't behave as I would expect.
我遇到了一个问题,其中std :: copy的行为不符合我的预期。 If anyone has an explanation, I would very much appreciate this.
如果有人有解释,我将非常感谢。
I completely understand the errors I get and a work-around is to use old-style memcpy, but if there is a solution, where I can use std::copy, I would appreciate this. 我完全理解我得到的错误,一种解决方法是使用旧式memcpy,但是如果有解决方案,我可以在其中使用std :: copy,我将不胜感激。
The error I get is: 我得到的错误是:
error: no matching function for call to 'begin(const float*&)' 错误:没有匹配的函数可以调用'begin(const float *&)'
and I'am using gcc 4.7.2-5 with C++11 enabled. 我正在使用启用了C ++ 11的gcc 4.7.2-5。
There errors I get for the std::copy within the set function 在set函数中,我对std :: copy有错误
#include <vector>
#include <array>
#include <algorithm>
#include <cstring>
class A {
public:
float data[3];
void set(const float c[3]) {
std::copy(std::begin(c),std::end(c), std::begin(data));
}
};
int main() {
const float a[3] = {1,2,3};
float b[] = {4,5,6};
std::copy(std::begin(a),std::end(a), std::begin(b));
return 0;
}
This function parameter 该功能参数
const float c[3]
is actually a pointer to float
, or const float*
. 实际上是一个指向
float
或const float*
的指针。 It is confusing, and is really used to document that the argument should be an array, but any float*
could be passed to it. 这很令人困惑,并且实际上是用来证明该参数应该是一个数组,但是任何
float*
都可以传递给它。 Inside the function, c
is a pointer and that is why std::begin
doesn't work. 在函数内部,
c
是指针,这就是为什么std::begin
不起作用的原因。
If you want to pass a reference to an array to a function, you need a different syntax: 如果要将对数组的引用传递给函数,则需要其他语法:
void set(const float (&c)[3]);
Alternatively, you can use a user-defined array type, std::array<float, 3>
. 另外,您可以使用用户定义的数组类型
std::array<float, 3>
。
Note that std::begin
and std::end
live in the <iterator>
header. 请注意,
std::begin
和std::end
在<iterator>
标头中。 Also note that you can use the old-school approach: 另请注意,您可以使用传统方法:
std::copy(c, c + 3, &data[0]);
const float c[3]
as a function parameter is longhand for const float* c
due to C legacy compatibility. const float c[3]
作为函数参数对于const float* c
是常用的,因为它具有C传统兼容性。
Try const float (&c)[3]
or std::array<float,3> const& c
or the like. 尝试
const float (&c)[3]
或std::array<float,3> const& c
等。
I like template<class T>using Type=T; Type<float[3]> const& c
我喜欢
template<class T>using Type=T; Type<float[3]> const& c
template<class T>using Type=T; Type<float[3]> const& c
myself. 我自己输入
template<class T>using Type=T; Type<float[3]> const& c
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.