我一直在尝试一个类似于元组的数据结构。它应该只包含每种类型的对象中的一种,并且每个对象都应该是一个c样式的PODS。它使用一种奇怪的方式访问它所持有的对象,并在其中返回对其派生类的引用。像:返回引用父类C++
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;
}
我使用的方法有可能的const_cast这一点,那么取消对它的引用,比static_casts它到T &。我正在使用的技术有没有陷阱?在我运行的测试中,这种设计似乎按预期执行。编号: const_cast是多余的。我对分配给这个指针的引用有一种误解。我应该static_casting T &来解除这个。
为什么你首先使用'const_cast'?你只是投射到相同的类型。 – 0x499602D2
如果你想添加'const',你可以使用'static_cast' – krzaq
@krzaq或者你只是改变返回类型为'const T&'并且使函数为'const' – user4407569