【发布时间】:2018-04-30 20:06:36
【问题描述】:
背景
我希望在临时基础上应用外观,而不是将它们烘焙到类本身中。但是我需要对数据进行操作,所以我需要this 可以从门面访问。这是一个小例子:
#include <array>
#include <iostream>
template <typename T>
struct x_getter
{
friend T;
double x() const
{
return (*real_self)[0];
}
void x(double new_x)
{
(*real_self)[0] = new_x;
}
private:
T* real_self = reinterpret_cast<T*>(this);
x_getter() = default; //prevents accidental creation
};
struct coordinates : std::array<double, 3>, x_getter<coordinates>
{
using std::array<double, 3>::array;
};
int main()
{
coordinates origin{};
std::cout << origin.x();
origin.x(12.7);
std::cout << ' ' << origin.x() << '\n';
}
It segfaults。不久前使用类似的东西,我很不幸能够逃脱它。
问题
如何使目标类类型的this 在外观类中可用?
我对班级布局的理解
在对象内部的某处,以无序的方式,有数组和x_getter。通过reinterpret_casting 它,我试图欺骗它认为this 是coordinates,但是当它执行operator[] 时,使用的偏移量有点偏离,它超出了对象,因此出现段错误。
【问题讨论】:
-
要获得派生类,您应该在方法内部使用
static_cast。 -
@VTT,您能否发布一个包含方法的答案,并且可能是一些链接供我阅读。谢谢,它有效。
标签: c++ language-lawyer c++17 crtp