部分专业化建议

时间:2015-10-12 13:39:15

标签: c++ partial dynamic-cast specialization

大家好我有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;
}

1 个答案:

答案 0 :(得分:1)

如果在编译时已知类型,则可以简单地使用函数重载。除了基类重载(或者如果需要还有通用函数模板)之外,这也有效。

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

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