无重复代码的多态函数调用
Polymorphic function call without duplicate code
假设一个层次结构的所有类都实现了一个模板成员函数g
。所有类共享调用此模板的另外两个函数f1
和f2
的相同实现:
struct A {
virtual void f1() {
g(5);
}
virtual void f2() {
g(5.5);
}
private:
template <typename T> void g(T) {std::cout << "In A" << std::endl;}
};
struct B: A {
// Can I get rid of this duplicate code?
virtual void f1() {
g(5);
}
virtual void f2() {
g(5.5);
}
private:
template <typename T> void g(T) {std::cout << "In B" << std::endl;}
};
struct C: A {
// Can I get rid of this duplicate code?
virtual void f1() {
g(5);
}
virtual void f2() {
g(5.5);
}
private:
template <typename T> void g(T) {std::cout << "In C" << std::endl;}
};
int main()
{
B b;
A &a = b;
a.f1();
return 0;
}
由于f1
和f2
的实现在所有类中都是相同的,我如何摆脱重复的代码,并使main
中的多态调用仍按预期工作(即产生输出"in B")?
A
、B
和C
中f1
和f2
的实现是不相同的。让我们将其限制为f1
s。一个调用名为::A::g<int>
的函数,另一个调用名称为::B::g<int>
的函数,第三个调用名称::C::g<int>
的函数。它们离完全相同还差得很远。
你能做的最好的事情就是有一个CRTP风格的基础:
template <class Derived>
struct DelegateToG : public A
{
void f1() override
{
static_cast<Derived*>(this)->g(5);
}
void f2() override
{
static_cast<Derived*>(this)->g(5.5);
}
};
class B : public DelegateToG<B>
{
friend DelegateToG<B>;
private:
template <class T> void g(T) { /*...*/ }
};
class C : public DelegateToG<C>
{
friend DelegateToG<C>;
private:
template <class T> void g(T) { /*...*/ }
};
您只需考虑模板函数使用的类特定内容,例如(在您的示例中)类名:
#include <iostream>
using namespace std;
class A
{
private:
virtual auto classname() const -> char const* { return "A"; }
protected:
template <typename T> void g(T) {cout << "In " << classname() << endl;}
public:
virtual void f1() { g(5); }
virtual void f2() { g(5.5); }
};
class B
: public A
{
private:
auto classname() const -> char const* override { return "B"; }
};
class C
: public A
{
private:
auto classname() const -> char const* override { return "C"; }
};
auto main()
-> int
{ static_cast<A&&>( B() ).f1(); }
相关文章:
- 如何在基类指针向量的元素上应用重载的多态函数
- uncrustify:如何将多行 C 函数调用的参数组合到一行上?
- 如何在不同类型的值之间进行选择以传递给多态函数?
- 尝试从多态函数中获得不同的输出
- 何时使用多个函数调用和 QTimer 调用析构函数?
- 获取 clang 格式以将多行函数调用的右括号放在单独的行上?
- 从指针向量呼叫多态函数到基类
- 不了解多态函数
- 对于相同的输入参数,多个函数调用返回不同的结果
- 将多个函数调用折叠为单个函数?
- 将多态函数应用于每个元组元素的结果类型
- C++中的多态性:调用重写的方法
- 类中的多态函数,实现抽象类
- 无重复代码的多态函数调用
- C++:多态性:调用超级函数
- 狗是动物,但列表<Dog>不是列表<Animal>。如何在泛型/多态函数中安全地使用它?
- 继承/多态性-调用子类的方法
- 使用多态指针调用函数
- 调用多态函数的正确形式.c++
- 以非多态方式调用虚拟函数的成本是多少