简体   繁体   中英

How to override a virtual function with a generic return type

I have a derived class from a template class. I'm overloading all the virtual functions in the derived class but i don't know what to use for return types

Base class:

#ifndef BASEDAO_H
#define BASEDAO_H

template <typename T>
class BaseDAO
{
protected:
    virtual void addObject(T)=0;
    virtual void removeObject(T)=0;
    virtual T getObject();
};

#endif // BASEDAO_H

Derived class:

#ifndef MEMBERDAO_H
#define MEMBERDAO_H
#include "basedao.h"
#include "member.h"


class MemberDAO : public BaseDAO<Member>
{
public:
    void addObject(Member);
    void removeObject(Member);
    Member getObject();
};

#endif // MEMBERDAO_H

All the other methods work. An error occurs, when i use Member as the return type. Thanks in advance.

The problem doesn't manifest in any compiler I tried, which may be the result of a transcription error?

One way to help yourself avoid some obvious boobytraps with this design is to use traits in the base definition:

#include <iostream>
#include <string>

template<typename T>
struct Base
{
#if HAVE_CPP11
    using value_type = T; // C++11
#else
    typedef T value_type;
#endif

    virtual value_type get() = 0;
};

struct Derived : public Base<std::string>
{
    value_type get() override { return "hello"; }
};

int main()
{
    Derived d;
    std::cout << d.get() << "\n";
}

The difference between returning value_type and std::string is just that we have indicated that the return type isn't chosen arbitrarily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM