虚函数和模板冲突 [英] Virtual functions and template clash

查看:25
本文介绍了虚函数和模板冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 pointAccumulator 的抽象基类.这个抽象的基础将用诸如返回所有点的平均值的函数之类的方法来填充.这两个类的示例如下所示:

I have an abstract base class for a pointAccumulator. This abstract base will be filled out with methods such as a function that returns mean of all the points. An example of these two classes is shown below:

class lala {
public:
    virtual someFunctions = 0;

    virtual bool isEmpty() = 0;
};


class lalaLower : public lala {
public:
    lalaLower(){}
    ~lalaLower(){}


    someFunctions

    template<class Archive> void serialize(Archive & ar, const unsigned int version) {
        ar & heights_;
    }

protected:
    std::deque<double> heights_;
};

正如您在代码中看到的,我还想使用 boost 序列化来保存这些类型.现在使用工厂模式,我相信你会像这样调用 pointAccumulator 类型:

As you can see in the code I would also like to use boost serialization in to save these types. Now using a factory pattern i believe that you call the pointAccumulator types like this:

lala *a1 = new lalaLower();

我的问题是如果我这样调用模板化的序列化方法将无法访问.此外,我不能在抽象类中使用模板化类,因为 C++ 不允许这样做.有没有办法解决这个问题?

My problem is that the templated serialize method will not be accessible if I call it this way. Also I cannot have the templated class in the abstract class as this is not allowed by c++. Is there a way to get around this?

我已经考虑过序列化的非侵入式方法,但这需要 heights_ 公开,这并不理想,也不是好的编程风格.我认为可能使用友元类或函数的方法可以通过访问变量来渗透类,同时仍然保持基类抽象?谁能解释一下这是如何工作的?

I have considered the non-intrusive method for serialization but that requires heights_ to be public which is not ideal, nor is it good programming style. I thought potentially a method using friend classes or functions could penetrate the class with access to the variables while still keeping the base class abstract? can anyone explain how this would work?

推荐答案

我认为使用友元类或函数是一个很好的解决方案,你可以添加像 Serializor 这样的新类

I think using friend classes or functions is a good solution, you could add new class like Serializor

这里是友元函数的例子

class Serializor;
class meanAccumulator : public pointAccumulator 
{ 
public:     
meanAccumulator(){}     
~meanAccumulator(){}     
double getHeight();     
void addHeight(double Height);     
void setHeight(double Height);     
bool isEmpty(){ return heights_.empty(); }      

protected:     std::deque<double> heights_; 
friend int Serializor::Func1( Serializor& );

};

请参阅http://msdn.microsoft.com/en-us/图书馆/ahhw8bzz.aspx

这篇关于虚函数和模板冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆