akosmaroy 0 Newbie Poster

while syntactically templates cannot be virtual functions, I wonder what approach to use when semantically this is what someone wants to do. for example, in my case I want to have a virtual function, because I'm using sub-classes while having a pointer to the base class, but I also want to use template functions, as the function I'm declaring has a parameter that I only know the concept of (iterator), but not the exact type.

here's the code that I'd want to accomplish from a semantic perspective, but which is not possible as it would include virtual function templates. I wonder what approach to use to achieve a similar result.

#include <vector>

// some base class A
class A {
public:
    A() {}
    virtual ~A() {}

    template<typename iterator>
    virtual void ize(iterator it) = 0;
};

// some derived class B
class B : public A {
public:
    int b;

    B() { b = 2; }
    virtual ~B() {}

    template<typename iterator>
    virtual void ize(iterator it) {
        *it = b;
        ++it;
    }
};

// some derived class C
class C : public A { ... };

// some factory method
A * factory(int type) {
    switch (type) {
        case 1: return new B();
        case 2: return new C();
          ...
        default: return 0;
    }
}


int main() {
    int type = 1;

    // get a subclass based on type
    A *a = factory(type);

    // use a with a vector
    std::vector<int> v;
    a->ize(std::back_inserter(v));

    // use a with an array
    int d[1];
    a->ize(d);


    return 0;
}