2

I have a class that inherits from 2 sets of base classes, according to variadic template arguments. One of those sets defines a virtual function. I want to do something like this but I'm not sure how it could compile:

template <class T>
struct Base {
    void virtual foo(T t) = 0;
};

template <class T>
struct Holder {
    T t;
};

template <class... T>
struct Child : Base<T>..., Holder<T>... {
    template <class O>
    void Base<O>::foo(O t) override {  // << this won't compile
        Holder<O>::t = t;
    }
};

LIVE

It gives the following error:

error: invalid use of incomplete type 'struct Base'

1
  • 2
    You cannot do that. You can combine a single Base and a single Holder into an intermediate class template, and then have Child inherit that intermediate class template variadically. Commented Jun 5, 2024 at 13:46

1 Answer 1

2

Basically virtual methods which are run time feature and not straight forward to combine with member function templates which are compile time feature.

To have virtual function you have to define it in advance so compile r can build proper virtual table. On other hand member function template generates new member function in place of usage.

In this case I would use this mix in this way:

template <class T>
struct Base {
    virtual ~Base() { }
    void virtual foo(T t) = 0;
};

template <class T>
struct Holder {
    T t = {};
};

template <typename T>
struct BaseHolderImplementer : Base<T>, Holder<T> {
    void foo(T t) override
    {
        std::cout << __PRETTY_FUNCTION__ << ' ' << Holder<T>::t << " -> " << t << '\n';
        Holder<T>::t = t;
    }
};

template <class... T>
struct Child : BaseHolderImplementer<T>... {
    using BaseHolderImplementer<T>::foo...;
};

void test(Base<int>& t)
{
    t.foo(323);
}

https://godbolt.org/z/hPEYPnvh3

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.