C++:在抽象类中需要静态函数

C++: Require static function in abstract class

本文关键字:静态函数 抽象类 C++      更新时间:2023-10-16

我正在尝试编写一个 c++ 抽象类,但我无法弄清楚如何要求此类的实现者包含静态函数。

例如:

class AbstractCoolThingDoer
{
    void dosomethingcool() = 0; // now if you implement this class 
                                        // you better do this
}
class CoolThingDoerUsingAlgorithmA: public AbstractCoolthingDoer
{
    void dosomethingcool()
    {
        //do something cool using Algorithm A
    }
}
class CoolThingDoerUsingAlgorithmB: public AbstractCoolthingDoer
{
    void dosomethingcool()
    {
        //do the same thing using Algorithm B
    }
}

现在我想做很酷的事情,而不详细说明很酷的事情是如何完成的。 所以我想做一些类似的事情

AbstractCoolThingDoer:dosomethingcool();

不需要知道很酷的事情是如何完成的,但这似乎需要一个既虚拟又静态的功能,这当然是一个矛盾。

理由是CoolThingDoerUsingAlgorithmB可能会在以后编写,希望需要完成很酷的事情的软件不必重写。

编辑:不确定我是否清楚我想要完成什么。 我有 3 个标准需要满足

    一个使用抽象酷事物做者的库,并且
  1. 永远不需要重写,即使编写了另一个库从未听说过的酷事物做家。

  2. 如果您尝试编写不符合所需结构的 coolthingdoer,则使用该库的可执行文件将无法编译。

  3. Coolthingdoer有一些必需的静态函数。

我可能正在追逐一个糟糕的设计,所以请指出我一个更好的设计。 我需要工厂吗?

也许

这样的事情会有所帮助(参见 ideone.com 示例):

#include <iostream>
class A
{
 protected:
  virtual void do_thing_impl() = 0;
 public:
  virtual ~A(){}
  static void do_thing(A * _ptr){ _ptr->do_thing_impl(); }
};
class B : public A
{
 protected:
  void do_thing_impl(){ std::cout << "B impl" << std::endl; }
};
class C : public A
{
 protected:
  void do_thing_impl(){ std::cout << "C impl" << std::endl; }
};
int main() 
{
 B b_;
 C c_;
 A::do_thing(&b_);
 A::do_thing(&c_);  
 return (0);
}

编辑:在我看来,OP不需要运行时多态性,而是不需要类实例的编译时多态性(当实现隐藏在派生类中时,使用static函数,不需要实例)。希望下面的代码有助于解决它(ideone.com 上的示例):

#include <iostream>
template <typename Derived>
struct A
{
  static void do_thing() { Derived::do_thing(); }
};
struct B : public A<B>
{
  friend A<B>;
 protected:
  static void do_thing() { std::cout << "B impl" << std::endl; }
};
struct C : public A<C>
{
  friend A<C>;
 protected:
  static void do_thing() { std::cout << "C impl" << std::endl; }
};
int main() 
{
 A<B>::do_thing();
 A<C>::do_thing();
 return (0);
}

编辑#2:如果用户不遵守所需的模式,要在编译时强制失败,以下是 ideone.com 的轻微修改:

#include <iostream>
template <typename Derived>
struct A
{
  static void do_thing() { Derived::do_thing_impl(); }
};
struct B : public A<B>
{
  friend A<B>;
 protected:
  static void do_thing_impl() { std::cout << "B impl" << std::endl; }
};
struct C : public A<C>
{
  friend A<C>;
 protected:
  static void do_thing_impl() { std::cout << "C impl" << std::endl; }
};
struct D : public A<D>
{
 friend A<D>;
};
int main() 
{
 A<B>::do_thing();
 A<C>::do_thing();
 A<D>::do_thing(); // This will not compile.
 return (0);
}
在我看来

,这是实现桥接模式的正确位置。也许这就是你(无意识地)愿意实现的目标。简而言之,您指定一个接口及其实现,然后调用您的 do_thing 方法,进而调用指向实现器类的指针上的实现。

C++示例