部分专业建议

Partial specialization advice

大家好我有this例子。通常在这种情况下我会使用访客模式。然而,出于某种原因,写 BaseDerivedADerivedB 的人更喜欢 dynamic_cast。请记住,我无法更改 BaseDerivedADerivedB 类。 我已经解决了部分专业化的铸造问题。请让我知道这是一个好的解决方案还是有更好的解决方案?

#include <iostream> 
using namespace std;

class CBase{};

class CDerivedA: public CBase{};

class CDerivedB : public CBase{};

class CDerivedC : public CBase{};

template <typename T>
void Draw(T* face)
{
    cout<<"Base"<<endl;
}

template <>
void Draw<>(CDerivedA* face)
{
    cout<<"A"<<endl;
}

template <>
void Draw<>(CDerivedB* face)
{
    cout<<"B"<<endl;
}

int main() {
    CDerivedA* a = new CDerivedA ();
    CDerivedB* b = new CDerivedB ();
    CDerivedC* c = new CDerivedC ();

    Draw(a);
    Draw(b);
    Draw(c);

    return 0;
}

如果类型在编译时已知,您可以简单地使用函数重载。这也适用于基础 class 重载(或者如果需要的话,通用函数模板)。

void Draw(CBase* face);
void Draw(CDerivedA* face);
void Draw(CDerivedB* face);

如果类型在运行时已知,并且您无法修改 classes(即添加虚函数),则需要某种调度机制。一种不涉及大量 classes 和样板代码的方法是 table 将类型映射到函数,例如std::map<std::type_index, std::function<void()>> 或类似的。由于查找和动态调度开销,它可能效率不高。