具有模板模板参数的CRTP派生类

问题描述

我正在设计一种具有以下结构的API,并且我正在模板-模板CRTP参数领域中寻求实用的设计建议。我对C ++模板比较陌生,请耐心等待。

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>) {
        ...
    }
}

代数和几何表示两个不同的算法类别,并且从每个类别派生出许多互斥的算法。几何算法的独特之处在于,它们需要使用一种代数方法进行初步猜测,这是我的问题。

对于每个几何“子类”,我想创建一个模板参数,该参数允许在保持原始CRTP模式的同时提供代数方法。实现此目标的最佳方法是什么?就需要template-template参数而言,我的想法是否有效?

解决方法

使用CRTP,派生类不必是模板。您继承基本类型的模板实例化,并将派生类型插入Derived中:

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

因此,如果您的派生类碰巧具有模板参数,并且您想引用自身,则只需插入模板参数即可。模板模板参数的工作方式相同。

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