2016-09-30 77 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