CRTP derived class with template template parameter

Viewed 238

I am designing an API that has the following structure and I am seeking practical design advice in the realm of template-template CRTP parameters. I am relatively new to templates in C++ so bear with my inexperience.

template<typename Derived>
struct FitCRTP {
    ...
}

template<typename Derived>
class FitBase : public FitCRTP<Derived> {
    ...
}

template<typename Derived>
class Algebraic : public FitBase<Derived> {
    Algebraic(const Matrix& data) {
        ...
    }
}

template<typename Derived, template<typename> class Alg>
class Geometric : public FitBase<Derived> {
    Geometric(const Matrix& data, Alg<someparam>) {
        ...
    }
}

Algebraic and Geometric represent two distinct classes of algorithms, and from each are derived a number of mutually exclusive algorithms. The Geometric algorithms are unique in that they require an initial guess produced by one of the Algebraic methods -- herein lies my problem.

For each of the Geometric "subclasses" I want to create a template parameter that allows for an Algebraic method to be supplied while maintaining the original CRTP schema. What is the best way to go about implementing this? Is my thinking valid as far as the need for a template-template parameter?

1 Answers

With CRTP, the derived class doesn't need to be a template. You inherit a template instantiation of the base type, with the derived type plugged into Derived:

class Algebraic : public FitBase<Algebraic> {
    Algebraic(const Matrix& data) { }
};

So, if your derived class happens to have a template parameter, and you want to refer to itself, just plug in the template parameters. Template template parameters work the same way.

template<template<typename> class Alg, typename someparam>
class Geometric : public FitBase<Geometric<Alg, someparam>> {
    Geometric(const Matrix& data, Alg<someparam>) { }
};

https://godbolt.org/z/qjvvK8

Related