我有一个 CRTP 类,为了在重构过程中 API 清晰,我希望有一个包含方法的命名匿名结构,而不是在类范围内拥有所有方法。问题是,这些方法需要访问外部作用域。例如:
template<typename T>
class sample_class {
public:
struct {
void do_something() {
auto& result = get_ref().something_else(); //get_ref() out of inner struct scope
...
}
} inner;
private:
T& get_ref() { return static_cast<T&>(*this); }
};
是否有一些技术可以实现这项工作?特别是 C++14 和 gcc7,因为我不相信匿名结构在技术上符合标准。
最佳答案
另一个类中的类没有指向封闭类的 this 指针的隐式指针。
如果您希望它具有指向封闭类实例的指针,请显式存储它。
struct {
void do_something() {
auto& result = p_sample->get_ref().something_else(); //get_ref() out of inner struct scope
...
}
sample* p_sample;
} inner;
或者传入指向方法的指针:
void do_something(sample* psample) {
auto& result = p_sample->get_ref().something_else(); //get_ref() out of inner struct scope
...
}
有一些方法可以使用指针算术来生成看似指向外部类的指针,但它们在 C++ 中受到极其复杂和危险的规则的限制。
除了一些访问/命名规则等之外,其他类中定义的类并不神奇。它们(理论上)可以存在于其他环境中; 内部
可以存在于堆栈中的某个地方,而不是在示例
中。
关于c++ - 是否有一种技术可以让匿名结构的命名实例引用封闭类中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71117785/