Home > Back-end >  How to make a class static variable which depends on the complete class type a constexpr?
How to make a class static variable which depends on the complete class type a constexpr?

Time:10-04

I have a class MyClass which has a static variable instance. The value of instance is a compile-time constant, but it depends on the complete type MyClass. Is there any way to make instance a constexpr?

// memchunk.hpp

#ifndef MEMCHUNK_HPP
#define MEMCHUNK_HPP

#include <new>
#include <utility>

enum class DestroyOption {
  Implicit,
  Explicit,
};
// a wrapper for placement new
template <class T, DestroyOption Opt = DestroyOption::Implicit> class MemChunk {
  alignas(T) char buf[sizeof(T)];

public:
  template <typename... Args> void construct(Args &&...args) {
    new (buf) T(std::forward<Args>(args)...);
  }
  void destroy() { get()->~T(); }
  constexpr T *get() { return reinterpret_cast<T *>(buf); }
  ~MemChunk() {
    if constexpr (Opt == DestroyOption::Implicit)
      destroy();
  }
};

#endif // MEMCHUNK_HPP
// myclass.cpp

#include "memchunk.hpp"

// struct MyClass; // forward declaration
// MemChunk<MyClass> obj; // error: incomplete type MyClass

class MyClass {
    static const MyClass *instance; // better to be constexpr
};
MemChunk<MyClass> obj;
const MyClass *MyClass::instance = obj.get();

CodePudding user response:

Use a function instead:

class MyClass {
    static constexpr MyClass* instance();
};

MemChunk<MyClass> obj;

constexpr MyClass* MyClass::instance() {
    return obj.get();
}

However, this is pointless because obj.get() cannot be used in a constexpr context (because of the reinterpret_cast, as mentioned in the comments).

Demo

  • Related