如何解决修复通用引用无法绑定到 gcc/g++ 中的打包结构字段和副作用
-
这与类似问题的其他答案不同。他们需要 调用方中的源代码修改。这解决了问题 被调用方 无需修改调用方代码。 Passing reference of packed struct member to template. gcc bug?
-
也
make_pair(packed_bitfield,packed_bitfield)
给出类似的编译 错误。 -
如果调用通用引用函数
f
的代码可以 改变了,我可以pass f(static_cast<const int &>(x.i)) or as_const(x.i)
到通用参考函数。
在什么情况下我的修复会失败?我是否遗漏了任何角落案例?
#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 举报,一经查实,本站将立刻删除。