基类中使用此指针的模板函数

Template function in base class using this-pointer

本文关键字:函数 指针 基类      更新时间:2023-10-16

考虑以下代码:

struct Base
{
    ~Base() {}
    virtual double operator()(double x) const = 0;
};
template<typename F, typename G> struct Compose;  //forward declaration of Compose
struct Derived1 : public Base    //plus many more derived classes
{
    virtual double operator()(double x) const {return x;}
    template <typename F>
    Compose<Derived1,F> operator()(const F& f) const {return Compose<Derived1,F>(*this,f);}
};
template<typename F, typename G>
struct Compose : public Base
{
     Compose(const F &_f, const G &_g) : f(_f), g(_g) {}
     F f;
     G g;
     virtual double operator()(double x) const {return f(g(x));}
};
void test()
{
    Derived1 f,g;
    auto h=f(g);
}

这里的compose类接受两个派生类f,g,并通过operator()返回compositum f(g(x))。

是否可以以某种方式避免在许多派生类中的每个派生类中使用显式定义,并在基类中添加一个函数?


编辑:为了更好地解释我想要的内容:原则上,我想在基类中添加如下内容

template<typename F> Compose<decltype(*this), F>
operator()(const F& f) {return Compose<decltype(*this), F>(*this,f);}

我尝试这样做是希望decltype(*this)能自动插入派生类的类型。但它似乎不是这样工作的。。。


解决方案:我终于找到了解决方法,那就是通过CRTP。然后基类采用形式

template<typename Derived>
struct Base
{
    ~Base() {}
    virtual double operator()(double x) const = 0;
    template<typename F> Compose<Derived, F>
    operator()(const F& f) {return Compose<Derived, F>(static_cast<Derived const&>(*this),f);}
};

并且导出的类是从导出的

struct Derived1 : public Base<Derived1>

假设Base是纯虚拟的,可以将模板函数移动到Base。所有派生类都必须实现double operator()(double x)并进行委托。

此外,我使用了Base指针而不是实例,因为正如您所指出的,否则它在Compose结构中不起作用(可能想更改那里的实现,使其不太容易泄漏…)

请注意,我从您的层次结构中取出了Compose(看起来它可以用于更通用的目的)-请随意将其放回(它将允许无休止的合成)。

此外,我删除了所有的const,因为struct需要为const对象提供默认的CTOR(可以随意放入)。

我重命名了composition操作符,因为我的编译器被客户端代码中的另一个operator()屏蔽了。

它需要清理核心就在那里:

template <typename F, typename G> struct Compose
{
     Compose( F* _f,  G &_g) : f(_f), g(_g) {}
      F* f;
     G g;
     double operator()(double x)  {return (*f)(g(x));}
};
struct Base
{
    ~Base() {}
    virtual double operator()(double x) = 0;
    template <typename F> Compose<Base,F> composeMeWith(F& f)  {return Compose<Base,F>(this,f);}    
};
struct D1 : public Base 
{
    virtual double operator()(double x)  { return 1.0; }
};
struct D2 : public Base 
{
    virtual double operator()(double x)  { return 2.0; }
};

一些客户端代码:

#include <iostream>
using namespace std;
int main(int argc, char** argv) 
{
     D1 d1;
     D2 d2;
    auto ret1 = d1.composeMeWith(d2);
    auto ret2 = d2.composeMeWith(d1);
    cout << ret1(100.0) << endl;
    cout << ret2(100.0) << endl;
}

您的Base类是纯抽象的,因此您不能这样做。您可以将Base类定义为一个具体的类,然后在具体的Base类中定义重载的函数调用运算符。请参阅以下代码:

struct Base
{
    ~Base() {}
    virtual double operator()(double x) const {return x;}
};
struct Derived1 : public Base    //plus many more derived classes
{
};
int main()
{
  Derived1 d;
  double x = d(1);
  std::cout << x << std::endl;
  return 0;
}