[英]How should I handle an multiple-inheritance conflict of types rather than methods?
假設我有:
class A { public: using foo_t = int; }
class B { public: using foo_t = int; }
class C : public A, public B { }
我想參考C::foo_t
。 是的,它必須是C::foo_t
,而不是C::A::foo_t
或C::B::foo_t
。 顯然,編譯器抱怨模棱兩可。 如果這些是方法,我可以使用虛擬繼承,也可以使用mixin來形成菱形或其他。 但是我應該對類型做什么? 我應該手動添加一條using語句嗎?
筆記:
使用語句確實足夠了:
class A { public: using foo_t = int; };
class B { public: using foo_t = int; };
class C : public A, public B { public: using A::foo_t; };
int main() {
C::foo_t v = 0;
}
這樣, C::foo_t
絕對是A::foo_t
(如注釋中正確建議的)。
如果要為C
定義foo_t
類型或新類型,則可以按照以下步驟進行操作:
class C : public A, public B { public: using bar_t = A::foo_t; };
這是一個最小的完整示例,其中使用sfinae而不是靜態斷言來驗證類型是否相同:
#include<type_traits>
class A { public: using foo_t = int; };
class B { public: using foo_t = int; };
class C { public: using foo_t = double; };
template<class T, class U,
std::enable_if_t<std::is_same<typename T::foo_t, typename U::foo_t>::value>* = nullptr>
class D: public T, public U { public: using T::foo_t; };
int main() {
D<A, B>::foo_t v = 0;
// the line below does not compile
//D<A, C>::foo_t v = 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.