Re: templates and virtual
Thomas Richter wrote:
Hi folks,
yes, templates and virtual member functions do not fit, I know. However,
I have here a situation where exactly that would be practical:
I have N worker classes that all provide the same interface, say:
class Interface {
public:
virtual double measure(const int *data1,const int *data2) = 0;
};
class A1 : public Interface {
// implements measure...
};
class A2 : public Interface {
// implements measure...
};
A clear application of virtual functions. Now, however, the same
function ("measure") is also required for a limited set of scalar types
that is known in advance. Say, "int", "short", "long" (doesn't matter
here). The implementation of "measure" is in all implementing interfaces
similar enough to share the code and generate it by a template.
(....)
class Interface {
public:
template <typename T>
virtual double measure(const T *data1,const T* data2) = 0;
};
with classes implementing the interface requiring to implement the
template for all types T from a set of types specified in advance.
Clearly, the above is not possible in C++ (how would I tell the compiler
which T's are part of the interface specifications.
Which alternatives exist to generate a class hierarchy similar to the
above, i.e. require implementing classes of an interface to build
templates for a given set of types?
How about simply using a list of pure virtual functions, since they're
limited anyway. These just forward to a templated function in the
implementing classes. See code example below.
br,
Martin
class Interface {
public:
// public interface is non-virtual:
template <typename T>
double measure(const T *data1,const T* data2) {
return do_measure(data1, data2);
}
private:
// Force specialization for all relevant datatypes:
virtual double do_measure(const int *data1, const int* data2) = 0;
virtual double do_measure(const double *data1, const double* data2) = 0;
// ...
};
class B1 : public Interface {
private:
// Note: Forward all specializations to the templated private funtion:
// (Could be done by a non-evil helper macro)
virtual double do_measure(const int *data1, const int* data2) {
return do_measure_impl(data1, data2);
}
virtual double do_measure(const double *data1, const double* data2) {
return do_measure_impl(data1, data2);
}
// ...
template <typename T>
double do_measure_impl(const T *data1,const T* data2) {
// algorithm here
return 3.14;
}
};
void f() {
Interface* p = new B1();
int a=1, b=2;
double res = p->measure(&a, &b);
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]