返回对父类c++的引用

Returning reference to parent class C++

本文关键字:引用 c++ 父类 返回      更新时间:2023-10-16

我一直在尝试一个类似元组的数据结构。它应该只包含每种类型的1个对象,并且每个对象应该是c风格的PODS。它使用一种奇怪的方式来访问它所持有的对象,它返回对它派生的类的引用。如:

template<class... Ts>
class Container : private Ts... 
{
public:
    template<class T>
    T& get_component() 
    {   //returns reference to base class specified by T
        return static_cast<T&>(* const_cast<Container<Ts...> *>(this));
    }
};

和打算这样使用:

struct A { int   x, y; };
struct B { float x, y; };
int main() 
{
    using namespace std;
    Container<A, B> foo;
    A& a_ref = foo.get_component<A>();
    a_ref.x = 5;
    a_ref.y = 10;
    const B& b_ref = foo.get_component<B>();
    cout << b_ref.x << endl;
    cout << b_ref.y << endl;
}
我使用的方法必须对this进行const_cast,然后对其解引用,然后将其静态转换为T&。在我使用的技术中有什么陷阱吗?在我运行的测试中,这个设计似乎与预期的一样。

编辑:const_cast是多余的。我对将引用赋值给this指针有一个误解。我应该是static_casting T&

据我所知,这可以简化为:

template<class... Ts>
class Container : private Ts... 
{
public:
    template<class T>
    T& get_component() 
    {
        return *this;
    }
    template<class T>
    const T& get_component() const
    {
        return *this;
    }
};

如果你被允许检索组件,我质疑为什么它们是私有基类。

代码的一个可能的问题是同一基类型多次出现,例如:

struct A {};
struct B : A {};
Container<A,B> container;
auto& a_ref = container.get_component<A>();

给出一个错误。您可以通过使用私有数据成员而不是私有基来避免类似的事情,这将只允许get_component在直接基上工作。