C++:在抽象类中需要静态函数
C++: Require static function in abstract class
我正在尝试编写一个 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 个标准需要满足
- 一个使用抽象酷事物做者的库,并且
永远不需要重写,即使编写了另一个库从未听说过的酷事物做家。
如果您尝试编写不符合所需结构的 coolthingdoer,则使用该库的可执行文件将无法编译。
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++示例
相关文章:
- 有没有办法按值将纯抽象类的所有子类传递给 C++ 中的函数?
- 将自定义函数传递到基抽象类中以延迟执行
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 从抽象类继承以创建另一个抽象类时,我应该重新声明所有虚函数吗?
- 类中静态函数C++意外结果
- 在工人类中使用不同类的静态函数进行实验
- 扩展包含静态函数的类
- 静态函数作为类模板参数-导致可维护性问题
- C++静态函数:放在类的范围之内或之外
- 返回虚拟函数的静态成员,对于抽象类缺少VT
- 静态函数到类的静态指针之间的区别是什么
- 通过此指针从静态函数调用类函数
- C++:在抽象类中需要静态函数
- 静态函数对类构造的好处
- 关于纯抽象类中的静态成员函数-设计模式
- 纯抽象类可以包含静态常量、静态方法或非虚析构函数吗?
- 引用静态函数作为类定义的一部分是否有任何开销?
- 从同一类的专门化模板的静态函数访问类模板成员
- 如何从同一个类的静态函数访问类的私有成员
- 如何从另一个类的函数中获取非静态函数的类函数指针?