2013-05-16 38 views
2

考慮:是否有可能使一個typedef僅對子類可見?

template <...> 
class InheritedByManyClasses 
{ 
public: 
    typedef InheritedByManyClasses<...> ParentClass; 
}; 

如果我做的那是多個類的父一子,有沒有什麼辦法鏈這個想法在一起嗎?

template<...> 
class ChildInheritedByMany : InheritedByManyClasses<...> 
{ 
public: 
    typedef ... ParentClass; // oops! now this class can't benefit from parent typedef 
}; 

有一些方法我可以在這只是可見孩子的孩子typedef

回答

1

沒有沒有。所有成員始終對當前課程可見。但是,有一個簡單的解決方法:

template<typename T> 
struct base_typedef_shim : T 
{ 
    typedef T ParentClass; 

    // the usual C++11 perfect constructor forwarding stuffs 
}; 

template <...> 
class InheritedByManyClasses 
{ 
}; 

template<...> 
class ChildInheritedByMany : public base_typedef_shim<InheritedByManyClasses<...>> 
{ 
}; 

template<...> 
class GrandChild : public base_typedef_shim<ChildInheritedByMany<...>> 
{ 
}; 
+0

我從每一個答案中學到了一些東西,但是這個答案最接近於回答我試圖問的東西。 –

5
using 

template<typename T> 
struct A { 
    protected: 
    using V = std::vector<T>; 
}; 

template<typename T> 
struct B : A<T> { 
    protected: 
    typename A<T>::V i; 
    public: 
    using A<T>::V; // If you want to make it public now 

}; 

int main() { 
    // A<int>::V i; // Not visible 
    B<int>::V i; // visible 
} 
+0

+1 from me。我實際上被我的老闆告知了在生產代碼中使用'using'。 – inetknght

1

你可以把typedef到子類,而不是:

template<...> 
class ChildInheritedByMany : InheritedByManyClasses<...> 
{ 
public: 
    typedef InheritedByManyClasses<...> ParentClass; 
}; 

另外,根據你的使用情況,std::is_base_of可能會派上用場。

2

讓它protected和孩子把typedef順序:

struct A 
{ 
}; 

struct B : public A 
{ 
protected: 
    typedef A Parent; 
}; 

struct C : public B 
{ 
protected: 
    typedef B Parent; 
}; 
+0

我不認爲這是OP的含義。如果我理解正確,他們希望有一個名稱來引用派生類「D」中的基類'B',並且*同時具有用於派生類「E」的*相同*名稱從'D'指代'D'。我可能會誤解,雖然 –

+0

@AndyProwl:已更新。是否有可能爲兒童課程自動生成_typedef_?我認爲他應該在所有的孩子中手動定義_typedefs_。 – deepmax

+0

對不起,我想我確實誤解了OP的想法。我認爲@ BenVoigt的回答澄清了它 –

相關問題