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
436 views
in Technique[技术] by (71.8m points)

c++ - Force explicit template instantiation with CRTP

I am trying to use a CRTPed base to hold some static initialization code like this:

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

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

Now, any class which 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 force instantiation of InitCRTP<WantInit>::init, I can either use dummy or use the explicit instantiation as shown above. Is there a way of getting around this with doing neither? I would like users of this pattern to be able to simply inherit from InitCRTP<WantInit> and not worry about anything else. If it helps, using C++11 is not an issue.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You could pass the variable as a reference template argument. Then the object is needed which causes an instantiation

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

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

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

...