我有一个程序,其中有很多嵌套的if / switch语句,这些语句在多个地方重复出现。我试图将其提取出来,并将开关放入模板方法类中,然后允许客户端重载他们想使用重载专门处理的哪个开关分支:
class TraitsA {};
class TraitsB : public TraitsA {};
class Foo
{
bool traitsB;
public:
// Whether or not a Foo has traitsB is determined at runtime. It is a
// function of the input to the program and therefore cannot be moved to
// compile time traits (like the Iterators do)
Foo() : traitsB(false) {}
virtual ~Foo() {}
bool HasTraitsB() const { return traitsB; }
void SetTraitsB() { traitsB = true; }
};
class SpecificFoo : public Foo
{
};
template <typename Client> //CRTP
class MergeFoo
{
protected:
Foo DoMerge(Foo&, const Foo&, int, TraitsA)
{
// Do things to merge generic Foo
}
public:
// Merge is a template method that puts all the nasty switch statements
// in one place.
// Specific mergers implement overloads of DoMerge to specify their
// behavior...
Foo Merge(Foo* lhs, const Foo* rhs, int operation)
{
const Client& thisChild = *static_cast<const Client*>(this);
SpecificFoo* lhsSpecific = dynamic_cast<SpecificFoo*>(lhs);
const SpecificFoo* rhsSpecific = dynamic_cast<const SpecificFoo*>(rhs);
// In the real code these if's are significantly worse
if (lhsSpecific && rhsSpecific)
{
if (lhs->HasTraitsB())
{
return thisChild.DoMerge(*lhsSpecific,
*rhsSpecific,
operation,
TraitsB());
}
else
{
return thisChild.DoMerge(*lhsSpecific,
*rhsSpecific,
operation,
TraitsA());
}
}
else
{
if (lhs->HasTraitsB())
{
return thisChild.DoMerge(*lhs, *rhs, operation, TraitsB());
}
else
{
return thisChild.DoMerge(*lhs, *rhs, operation, TraitsA());
}
}
}
};
class ClientMergeFoo : public MergeFoo<ClientMergeFoo>
{
friend class MergeFoo<ClientMergeFoo>;
Foo DoMerge(SpecificFoo&, const SpecificFoo&, int, TraitsA)
{
// Do things for specific foo with traits A or traits B
}
};
class ClientMergeFooTwo : public MergeFoo<ClientMergeFoo>
{
friend class MergeFoo<ClientMergeFooTwo>;
Foo DoMerge(SpecificFoo&, const SpecificFoo&, int, TraitsB)
{
// Do things for specific foo with traits B only
}
Foo DoMerge(Foo&, const Foo&, int, TraitsA)
{
// Do things for specific foo with TraitsA, or for any Foo
}
};
但是,这无法编译(至少在
ClientMergeFooTwo
的情况下),表示无法将Foo&转换为SpecificFoo&。有什么想法会导致转换失败,而不是在MergeFoo
中选择完美的泛型重载吗?编辑:嗯,鉴于我尝试编写它的速度,这个psuedocode示例显然做得不好。我已经纠正了一些错误...
最佳答案
有什么想法为什么会失败,而不是在MergeFoo中选择完美的泛型重载?
是的,因为有名称隐藏规则。如果派生类中的函数与基类中的函数具有相同的名称,则基类函数为“隐藏”,它甚至不查看所涉及函数的参数。
就是说,解决方案很简单:在派生类中提供基类版本,并在公共部分添加简单的using MergeFoo::DoMerge
即可。