返回对父类c++的引用
Returning reference to parent class C++
我一直在尝试一个类似元组的数据结构。它应该只包含每种类型的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
在直接基上工作。
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 如何引用基类的派生类?