0

我正在尝试编写一个 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. 一个使用 abstractcoolthingdoer 并且永远不需要重写的库,即使编写了另一个库从未听说过的coolthingdoer。

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

  3. coolthingdoer 有一些需要的静态函数。

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

4

2 回答 2

2

也许,这样的事情会有所帮助(参见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);
}
于 2013-09-09T22:32:27.523 回答
0

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

C++ 示例

于 2013-09-09T23:04:35.377 回答