gpt4 book ai didi

c++ - 如何继承成员函数以便它始终返回对派生实例的引用?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:04:14 24 4
gpt4 key购买 nike

我正在开发一个迭代器系列,其中所有迭代器类 X 都有 X& operator++() {++x;返回 *this},所以将它放在一个公共(public)基类中似乎是个好主意。不幸的是,返回类型发生了变化,因为它应该始终返回对派生类的引用。

下面说明了这个问题。我想让 f() 工作,但我能想出的唯一解决方法是 g()h(),它们是不满意:

struct A {
A& f() {return *this;}

template <typename T>
T& g() {return *(T*)this;}

template <typename T>
T& h(T& unused) {return *(T*)this;}
};

struct B : A {
int x;
B(int x) : x(x) {}
};

int main() {
B b(12);

//B b1 = b.f(); // error: conversion from 'A' to non-scalar type 'B' requested

B b2 = b.g<B>(); // works
B b3 = b.h(b); // works
}

有没有办法让 B b1 = b.f(); 工作?也许使用 C++11 特性?

最佳答案

使用 CRTP :

template<class Derived>
struct A {
Derived& f() {return static_cast<Derived&>(*this);}
};

struct B : A<B> {
int x;
B(int x) : x(x) {}
};

关于c++ - 如何继承成员函数以便它始终返回对派生实例的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24137772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com