从'现代C++设计'的以下技术,我正在实现一个具有各种编译时优化的持久性库。我想派遣功能,模板化的成员变量的能力,如果该变量从给定的类派生:基于编译时类型的调度
template<class T, template <class> class Manager = DefaultManager> class Data
{
private:
T *data_;
public:
void Dispatch()
{
if(SUPERSUBCLASS(Container, T))
{
data_->IKnowThisIsHere();
}
else
{
Manager<T>::SomeGenericFunction(data_);
}
}
}
凡SUPERSUBCLASS是一个编译时宏来确定对象继承。当然,在所有T从Container继承的情况下(或者T是一个内部类型等),这都会失败,因为编译器会正确地抱怨IKnowThisIsHere()不是数据成员,即使这条代码路径永远不会被遵循,如T = int预处理后所示:
private:
int *data_;
public:
void Dispatch()
{
if(false)
{
data_->IKnowThisIsHere();
编译器明显抱怨此代码,即使它永远不会执行。使用的dynamic_cast的建议也不起作用,因为再次类型转换试图在编译时这是不可能的(例如使用T =双,的std :: string):
void Dispatch()
{
if(false)
{
dynamic_cast<Container*>(data_)->IKnowThisIsHere();
error: cannot dynamic_cast '((const Data<double, DefaultManager>*)this)->Data<double, DefaultManager>::data_' (of type 'double* const') to type 'class Container*' (source is not a pointer to class)
error: cannot dynamic_cast '((const Data<std::string, DefaultManager>*)this)->Da<sttad::string, DefaultManager>::data_' (of type 'struct std::string* const') to type 'class Container*' (source type is not polymorphic)
我真的需要模拟(或确实劝说!)如果T从Container继承,则编译器发出一组代码;如果不从Container继承,则编译器发出一组代码。
有什么建议吗?
感谢长久 - 这正是我之后。 – user23167 2008-09-28 16:07:10