c++ - 访问另一个结构中的结构字段
问题描述
假设我有结构
struct A
{
int x;
};
并且可以通过以下方式引用 x 字段
&A::x
我的问题是,在以下情况下(C++14)我可以做类似的事情(参考 x)吗?:
struct A
{
struct B
{
int x;
};
B b;
};
好的,还有更复杂的例子:
这有效:
struct A
{
int x;
};
template <typename U, typename V, typename W>
void setField(U& object, V U::* field, W&& value)
{
object.*field = std::forward<W>(value);
}
int main()
{
auto x = 5;
A a;
a.x = 0;
std::cout << a.x << std::endl;
setField(a, &A::x, x);
std::cout << a.x << std::endl;
}
当我想获得更深层次的变量时,它不会:
struct A
{
struct B
{
enum myEnum
{
E_0 = 0,
E_1 = 1
};
myEnum e;
};
B b;
};
template <typename U, typename V, typename W>
void setField(U& object, V U::* field, W&& value)
{
object.*field = std::forward<W>(value);
}
int main()
{
auto m_enum = A::B::myEnum::E_0;
A a;
a.b.e = m_enum;
std::cout << a.b.e << std::endl;
setField(a, &A::B::e, m_enum);
std::cout << a.b.e << std::endl;
}
错误日志:
31:31: error: no matching function for call to 'setField(A&, A::B::myEnum A::B::*,A::B::myEnum&)'
31:31: note: candidate is:
20:6: note: template<class U, class V, class W> void setField(U&, V U::*, W&&)
20:6: note: template argument deduction/substitution failed:
31:31: note: deduced conflicting types for parameter 'U' ('A' and 'A::B')
解决方案
你应该写:
setField(a.b, &A::B::e, m_enum);
代替
setField(a, &A::B::e, m_enum);
推荐阅读
- flutter - 在 `flyer` 包中找不到 `bin\flyer.dart`
- javascript - 使用 map() 或类似函数以以下格式返回数组数据
- sql - 获取多列的 NULL 值百分比
- reactjs - Safari 错误“无法在严格模式下的嵌套块中声明函数”
- javascript - 异步或延迟(或延迟)CSS 加载
- react-native - 在外部渲染功能中反应原生渲染组件
- .net - 如何为 webapi 2.0 项目实施健康检查
- c++ - 通过链接QT c ++加载文件
- java - 如何将资源名称保留在 anylogic 中的实体代理中?
- python - Kivy 如何使用 popup.dismiss() 触发屏幕 on_enter/on_pre_enter?