We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,099 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

mixing virtual functions and template functions - how?

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;
}
1
Contributor
0
Replies
1
View
akosmaroy
Newbie Poster
1 post since Nov 2009
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0720 seconds using 2.68MB