Pattern problems with Barton and Nakman

I am trying to implement a class using the tricks of Barton and Nackman to avoid dynamic dispatch. (I write MCMC code where performance is important.) I'm not an expert in C ++, but the main trick works for me elsewhere. However, I now have a case where you need to create a template for a second derived class. This creates problems. The outline of my code is:

// Generic step class template<class DerivedStepType> class Step { public: DerivedStepType& as_derived() { return static_cast<DerivedStepType&>(*this); } void DoStep() { return as_derived.DoStep(); } }; // Gibbs step template<class DerivedParameterType> // THIS IS THE PROBLEM class GibbsStep : public Step<GibbsStep> { public: GibbsStep(DerivedParameterType new_parameter) { } void DoStep() { } }; 

The task is template<class DerivedParameterType> and the next <GibbsStep> (from the trick of Barton and Nakman). Using g ++ v 4.01 (OSX), I get the following error:

 ./src/mcmc.h:247: error: type/value mismatch at argument 1 in template parameter list for 'template<class DerivedStepType> class Step' ./src/mcmc.h:247: error: expected a type, got 'GibbsStep' 

Everything compiles fine if the template<class DerivedParameterType> drops out and replace DerivedParameterType with, say, double .

Any ideas?

+4
source share
2 answers

GibbsStep is a template class and requires instantiation when used in public Step<GibbsStep> . You must change it to public Step<GibbsStep<DerivedParameterType> >

+7
source

Naveen is right, but what you show here is not a Barton-Nakman trick. This is CRTP (Curiously Recurring Template Pattern). You can read about it here:

http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Curiously_Recurring_Template_Pattern

The Burton-Nackman trick deals with limited template expansion and has been replaced by specialization template semantics. You can read about it here:

http://en.wikipedia.org/wiki/Barton-Nackman_trick

Regards, Hovhannes

+1
source

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


All Articles