【问题标题】:CRTP derived class with template template parameter带有模板模板参数的 CRTP 派生类
【发布时间】:2020-09-07 22:26:35
【问题描述】:

我正在设计一个具有以下结构的 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 模式的同时提供代数方法。执行此操作的最佳方法是什么?就需要模板模板参数而言,我的想法是否有效?

【问题讨论】:

  • someparam 突然从何而来?
  • 澄清一下:它并不意味着代表任何实质性的东西——它是这个问题的占位符,因为我不完全确定应该去那里
  • 看来CRTP与Geometric/Algebraic关系没有任何关系;毕竟,它是您想要的实际派生类。为什么不直接使用class Alg——在类或构造函数上根据其用途使用?

标签: c++ templates c++17 crtp


【解决方案1】:

使用 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

【讨论】:

    猜你喜欢
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多