2016-09-30 164 views
1

我一直在尝试一个类似于元组的数据结构。它应该只包含每种类型的对象中的一种,并且每个对象都应该是一个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 &来解除这个。

+1

为什么你首先使用'const_cast'?你只是投射到相同的类型。 – 0x499602D2

+0

如果你想添加'const',你可以使用'static_cast' – krzaq

+1

@krzaq或者你只是改变返回类型为'const T&'并且使函数为'const' – user4407569

回答

1

据我可以告诉这可以只是简单:

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立即生效。

+0

其中一个原因是解决歧义,说foo.x是不明确的,因为A和B都有成员x。 – Brian

+0

@Brian:如果你使用公共基地,那么你可以简单地使用'A&a_ref = foo;'和'get_component'就没有必要了。 – user4407569