2012-10-18 41 views
1

有人問我以下的問題提供解決方案:如何使用靜態常量結構從一個類作爲一個真正的常量 - 即數組大小

有一個結構定義一些int參數:

struct B { 
    int a; 
    int b; 
}; 

一個想要將此結構定義爲其他類中的常量靜態成員(不僅此class A-還有其他類預計具有相同的常量集)

而且一個想利用他們作爲真正的整型常量:

// .h file 
class A { 
public: 
    static const B c; // cannot initialize here - this is not integral constant 
}; 
// .cpp file 
const B A::c = {1,2}; 

但不能使用此常數進行例如數組:

float a[A::c.a]; 

有什麼建議?

回答

2

如果您A::cconstexpr您可以在線初始化它,使用它的成員爲一個常數:

struct A { 
    static constexpr B c = {1, 2}; 
}; 

float a[A::c.a]; 
+0

我不能使用它 - 「對4.6的conscxpr的支持首先加入到GCC中」 - 我們有更早的版本。但對於更新的編譯器,您的解決方案比我的(+1)更好。 – PiotrNycz

1

我找到的解決方案是用const成員將struct更改爲templatestruct

template <int AV, int BV> 
struct B { 
    static const int a = AV; 
    static const int b = BV; 
}; 
template <int AV, int BV> 
const int B<AV,BV>::a; 
template <int AV, int BV> 
const int B<AV,BV>::b; 

與用法:

// .h file 
class A { 
public: 
    typedef B<1,2> c; 
}; 

和陣列:

float a[A::c::a]; 
//   ^^ - previously was . (dot) 
+0

W你沒有發佈在你的答案嗎? –

+0

@DenisErmolin他應該在哪裏發佈解決方案? –

+0

不是非常有用,但恕我直言可愛:) – davka

相關問題