2010-05-16 49 views
3

因爲一個類裏面靜態常量數據實際上只是命名空間糖常量我認爲添加靜態常量數據的結構已經定義

struct A { 
    float a; 

    struct B { 
     static const int b = 2; 
    }; 

}; 

將相當於

struct A { 
    float a; 
}; 

struct A::B { 
    static const int b = 2; 
}; 

什麼類似。在C++中可以這樣做嗎?對於我來說,使用這樣的信息來標記我從第三方庫中抽取的類定義會很有用。

+0

您有什麼具體要求?第一個塊相當於'struct A {float a;結構B; }; struct A :: B {static const int b = 2; };' – 2010-05-16 23:19:44

回答

1

不,你不能這樣重新定義類。

如果你想標記已經定義的類,你可以非侵入性地使用例如模板特:

template<class T> struct tagged; 

template<> struct tagged<A> { 
    static const int b = 42; 
}; 
3

不能重新打開在C++結構/類的定義,所以你能做的最好的是創建第三方結構的衍生版本,並添加您的常量方式:

struct My_A : public A 
{ 
    static const int b = a; 
}; 

否則,您可以使用基於struct typeid的鍵來維護常量的映射。

我也很喜歡喬治的想法。