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>
virtualvoid ize(iterator it) = 0;
};
// some derived class B
class B : public A {
public:
int b;
B() { b = 2; }
virtual ~B() {}
template<typename iterator>
virtualvoid 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: returnnew B();
case 2: returnnew 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);
delete a;
return 0;
}
kbw, yes, I do have an understanding on how virtual functions are implemented.
and yes, the two concepts really go against each other. though one could force the compiler generate code for _all_ known virtual functions for each new template invocations encountered, instead of code generation on the fly :) this would of course add functions to the vtable of all of these classes.
but, if not so - how can one solve this issue? write a virtual function that can accept a concept as a parameter, instead of a specific class?
Just off the top of my head, and knowing nothing about what you are trying to do, you might be able to use boost::variant<> coupled with boost::static_visitor<>. Or make everything a template.