views:

254

answers:

2

I'm trying to implement class using the Barton and Nackman trick to avoid dynamic dispatch. (I'm writing MCMC code where performance matters.) I'm not a C++ expert but the basic trick is working for me elsewhere. However I now have a case where the second derived class needs to be templated. This seems to cause 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 problem is template<class DerivedParameterType> and the following <GibbsStep> (from the Barton and Nackman trick). 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 a drop template<class DerivedParameterType> and replace DerivedParameterType with, say, double.

Any ideas?

+7  A: 

GibbsStep is a template class and requires instantiation while you are using in public Step<GibbsStep> . You should change it to public Step<GibbsStep<DerivedParameterType> >

Naveen
small correction: GibbsStep is a class template and not a template class ;)
ovanes
+1  A: 

Naveen is right, but what you show here is not a Barton-Nackman 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

Burton-Nackman trick deals with restricted template expansion and was superseded by template specialization semantics. You can read more about it here:

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

With Kind Regards, Ovanes

ovanes
re “… was superseded by template specialization semantics” – not completely. There are still some uses, as shown for example in the Wikipedia article. Concept maps in C++0x will eventually replace this use of the Barton-Nackmann trick.
Konrad Rudolph
Yes I know, I did not want to overcomplicate the post.
ovanes