我收到错误
绑定“const double”到类型“double&”丢弃限定符的引用
汇编时:
g++ -std=c++11 main.cpp
main.cpp: In function ‘Point square(const Point&)’:
main.cpp:14:28: error: binding ‘const double’ to reference of type ‘double&’ discards qualifiers
  for(double &a:{Q.x,Q.y,Q.z})
                            ^虽然网上还有关于这个错误的其他问题,但我正在寻找这个特定代码的解决方案。我坚持用ranged作为。
#include <iostream>
#include <vector>
class Point
{
public:
    double x,y,z;
};
Point square(const Point &P)
{
    Point Q=P;
    for(double &a:{Q.x,Q.y,Q.z})
        a*=a;
    return Q;
}
int main()
{
    Point P{0.1,1.0,10.0};
    Point Q=square(P);
    std::cout<<"----------------"<<std::endl;
    std::cout<<"Q.x: "<<Q.x<<std::endl;
    std::cout<<"Q.y: "<<Q.y<<std::endl;
    std::cout<<"Q.z: "<<Q.z<<std::endl;
    std::cout<<"----------------"<<std::endl;
    return 0;
}发布于 2018-01-09 03:40:36
{Q.x,Q.y,Q.z}在for上下文中创建的初始化程序列表仍然基于单独的值数组。即使您设法修改了这些值,它仍然不会影响您的Q,这显然是您的意图。但是无论如何您都不能修改它们,因为该数组由const元素组成(编译器就是这样告诉您的)。
如果你想要一个远程for,你可以使用C时代的老把戏。
for (double *a : { &Q.x, &Q.y, &Q.z })
  *a *= *a;或者,或者,或者
for (auto a : { std::ref(Q.x), std::ref(Q.y), std::ref(Q.z) })
  a *= a;发布于 2018-01-09 04:07:18
当然,正确的答案是:
for_each(std::tie(x, y, z), [](auto& a){a *= a;});
定义如下:
template <typename Tuple, typename F, std::size_t ...Indices>
void for_each_impl(Tuple&& tuple, F&& f, std::index_sequence<Indices...>) {
    using swallow = int[];
    (void)swallow{1,
        (f(std::get<Indices>(std::forward<Tuple>(tuple))), void(), int{})...
    };
}
template <typename Tuple, typename F>
void for_each(Tuple&& tuple, F&& f) {
    constexpr std::size_t N = std::tuple_size<std::remove_reference_t<Tuple>>::value;
    for_each_impl(std::forward<Tuple>(tuple), std::forward<F>(f),
                  std::make_index_sequence<N>{});
}
int main(){
    double x, y, z;
    for_each(std::tie(x, y, z), [](auto& a){a *= a;});
}https://stackoverflow.com/questions/48161048
复制相似问题