微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

修复通用引用无法绑定到 gcc/g++ 中的打包结构字段和副作用

如何解决修复通用引用无法绑定到 gcc/g++ 中的打包结构字段和副作用

在什么情况下我的修复会失败?我是否遗漏了任何角落案例

#include<iostream>
using namespace std;

template<typename T> 
int f(T&& args) {
    return args;
}

struct X {
    char c;
    unsigned int i;
} __attribute__((packed));

int main() {
    X x;
    x.i = 3;
    cout <<"x.i= "<<f(x.i)<<endl;
    return 0;
}
test3.cpp: In function ‘int main()’:
test3.cpp:16:22: error: cannot bind packed field ‘x.X::i’ to ‘unsigned int&’
   16 |  cout <<"x.i= "<<f(x.i)<<endl;
      |                    ~~^

为了解决这个问题,添加 const T && ref 通用引用和另一个重载模板函数 f(const L& arg),它仅在 L 是非右值引用时才被实例化。 新代码变成

template<typename T>
expr_lhs<const T> f(const  T &&  head)
{
        cout <<"in const universal ref ";
        return expr_lhs<const T>(forward<const T>( head )) ;
}

template<typename T,typename enable_if<  !is_rvalue_reference<T>::value,void >::type* = nullptr >
int f(const T &head){
        cout <<"in const non rvalue ref ";
        return 17;
}

编译并产生输出

  • 5= 在 const 通用参考 5 中
  • temp 右值 = 在 const 通用引用 0 中
  • rvalue = 在 const 通用引用 3 中
  • i = in const nonrvalue ref 17
  • x.i= in const nonrvalue ref 17

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。