Force template instantiation using CRTP

I am trying to use a CRTP base to store some static initialization code as follows:

template <typename T>
class InitCRTP
{
public:
static InitHelper<T> init;
};

template <typename T> InitHelper<T> InitCRTP<T>::init;

Now any class that needs to do the work in InitHelper<T>can do this:

class WantInit : public InitCRTP<WantInit>
{
  public:
  void dummy(){init;}//To force instantiation of init 
};
template class InitCRTP<WantInit>;//Forcing instantiation of init through explicit instantiation of `InitCRTP<WantInit>`.

To create an instance InitCRTP<WantInit>::init, I can either use dummyor use an explicit instantiation, as shown above. Is there a way around this without doing either? I would like users of this template to simply inherit from InitCRTP<WantInit>and not worry about anything else. If this helps, use is C++11not a problem.

+4
source share
1 answer

. ,

template <typename T, T /*unnamed*/>
struct NonTypeParameter { };

template <typename T>
class InitCRTP
{
public:
     static InitHelper init;
     typedef NonTypeParameter<InitHelper&, init> object_user_dummy;
};
+9

Source: https://habr.com/ru/post/1548260/


All Articles