Jerome
Jerome

Reputation: 25

Mixing virtual and templates

I know there are some some pitfalls when mixing inheritance and templates, but I'd like to know if the code below (which compiles and seems to run well) is "legal" and wellformed.

struct ISession {
    virtual ~ISession() = deafult;
    virtual void run() = 0;
};

template <typename Derived>
struct SessionBase : public ISession {
    SessionBase() {
        static_assert(is_base_of_v<SessionBase<Derived>, Derived>);
    }

    void run() override {
        derived().connect();
    }
    
    Derived& derived() {
        return static_cast<Derived&>(*this);
    }
};

struct PlainSession : public SessionBase<PlainSession> {
    void connect() {
        // do connect plain
    }
};

struct SslSession : public SessionBase<SslSession> {
    void connect() {
        // do connect ssl
    }
};

int main(int argc, char *argv[])
{
    list<unique_ptr<ISession>> sessions;
    sessions.emplace_back(make_unique<PlainSession>());
    sessions.emplace_back(make_unique<SslSession>());
    for_each(sessions.begin(), sessions.end(), [](auto& session) { session->run(); });
}

Upvotes: 2

Views: 216

Answers (1)

BoP
BoP

Reputation: 3150

The "pitfall" is that you cannot have a member template that is also virtual. That would result in an unknown number of virtual functions, potentially growing for each new use of the class.

template<typename T>
virtual void use(T);   // not possible

As long as it is either a template or virtual, but not both, it is ok.

Upvotes: 1

Related Questions