简体   繁体   English

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

[英]CRTP derived class with template template parameter

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.我正在设计一个具有以下结构的 API,我正在寻求模板模板 CRTP 参数领域的实用设计建议。 I am relatively new to templates in C++ so bear with my inexperience.我对 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>) {
        ...
    }
}

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.对于每个几何“子类”,我想创建一个模板参数,允许在保持原始 CRTP 模式的同时提供代数方法。 What is the best way to go about implementing this?执行此操作的最佳方法是什么? Is my thinking valid as far as the need for a template-template parameter?就需要模板模板参数而言,我的想法是否有效?

With CRTP, the derived class doesn't need to be a template.使用 CRTP,派生类不需要是模板。 You inherit a template instantiation of the base type, with the derived type plugged into Derived :您继承基类型的模板实例化,派生类型插入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 https://godbolt.org/z/qjvvK8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM