开发者

in-class initialization of non-integral static data

So I just learned via a compiler error that in-class initialization of arrays is invalid (why?). Now I would like to have some arrays initialized in a template class, and unfortunatly the contents depend on the template parameter. A condensed testcase looks like this:

template<typename T>
struct A {
    T x;
    static const int len = sizeof(T);         // this is of course fine
    static const int table[4] = { 0, len, 2*len, 3*len };    //this not
}

Any idea how to pull out the constant array?

开发者_如何学编程

EDIT: Added the 'int's.


Just as you'd do it without templates; put the initialization outside the class' declaration:

template<class T>
const int A<T>::table[4] = { 0, len, 2*len, 3*len };


 class Y
  { 
     const int c3 = 7; // error: not static 
     static int c4 = 7; // error: not const static const
     float c5 = 7; // error not integral
  };

So why do these inconvenient restrictions exist? A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

for more detail read : How do I define an in-class constant?



template <typename T, int index>
struct Table {
   static const len = sizeof(T);        
   static const value = len*index;
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜