Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

c++ - Proper initialization of static constexpr array in class template?

Static class members in C++ have caused a little confusion for me due to the standard's verbiage:

9.4.2 Static data members [class.static.data]

The declaration of a static data member in its class definition is not a definition...

However a constexpr is required to be initialized (AFAIK, couldn't find a quote from the standard) at its declaration (e.g., in the class definition).

Because of the restrictions on constexpr I had actually forgotten about the requisite for static members to be defined outside of the class, until I tried accessing a static constexpr array. This related question provides the correct way of defining the array member, but I'm interested as to the implications on this definition in a class template.

This is what I ended up with:

template<typename T>
class MyClass
{
private:
  static constexpr std::size_t _lut[256] = { /* ... */ };
  T _data;

public:
  static constexpr std::size_t GetValue(std::size_t n) noexcept
  {
    return _lut[n & 255];
  }

  // ...
};

template<typename T>
constexpr std::size_t MyClass<T>::_lut[256];

Is this the right syntax? Particularly the use of template in the definition feels awkward, but GCC seems to be linking everything appropriately.

As a follow-up question, should non-array static constexpr members be similarly defined (with template definition outside of class)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In case it helps anyone out, the following worked for me with GCC 4.7 using constexpr:

template<class T> class X {
  constexpr static int s = 0;
};
template<class T> constexpr int X<T>::s; // link error if this line is omitted

I'm not making any claims of whether this is "proper". I'll leave that to those more qualified.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...