有可能與C++ 11和decltype
。爲此,當成員從基類繼承時,我們將利用指向成員的指針不是指向派生類的指針。
例如:
struct base{
void f(){}
};
struct derived : base{};
類型的&derived::f
將void (base::*)()
,不void (derived::*)()
。這在C++ 03中已經是真實的,但是如果沒有真正指定它,就不可能獲得基類的類型。隨着decltype
,這很容易,只需要這個小功能:
// unimplemented to make sure it's only used
// in unevaluated contexts (sizeof, decltype, alignof)
template<class T, class U>
T base_of(U T::*);
用法:
#include <iostream>
// unimplemented to make sure it's only used
// in unevaluated contexts (sizeof, decltype, alignof)
template<class T, class R>
T base_of(R T::*);
struct base{
void f(){}
void name(){ std::cout << "base::name()\n"; }
};
struct derived : base{
void name(){ std::cout << "derived::name()\n"; }
};
struct not_deducible : base{
void f(){}
void name(){ std::cout << "not_deducible::name()\n"; }
};
int main(){
decltype(base_of(&derived::f)) a;
decltype(base_of(&base::f)) b;
decltype(base_of(¬_deducible::f)) c;
a.name();
b.name();
c.name();
}
輸出:
base::name()
base::name()
not_deducible::name()
作爲最後一個例子顯示,你需要使用一個部件,其實際上是您感興趣的基類的繼承成員。
再有更多的缺陷,但是:成員也必須明確地標識一個基類成員:
struct base2{ void f(){} };
struct not_deducible2 : base, base2{};
int main(){
decltype(base_of(¬_deducible2::f)) x; // error: 'f' is ambiguous
}
這是你能得到,雖然是最好的,沒有編譯器支持。
來源
2012-01-03 08:32:06
Xeo
使用['std :: is_base_of '](http://stackoverflow.com/questions/2910979/how-is-base-of-works) – iammilind 2012-01-03 07:57:41
@iammilind:這僅用於測試如果一個類是基礎另一個,你必須知道基類已經測試過。 – Xeo 2012-01-03 07:58:09
你需要什麼?我不認爲這是可能的,但也許有解決實際問題的不同方法。 – 2012-01-03 08:06:49