Tempate classes for vector and non-vector types

Hello.

I am trying to build a template class which can take both vector and non-vector types as the input. For example, a member function of the class takes input and performs constant multiplication. The problem is, depending on whether the object is defines with a vector or non-vector type, the operation would be different. That is, for non-vector types, the multiplication is straightforward. But, for vector types, it should be element-wise multiplication - additional iteration for the elements is needed. Therefore, it seems that the member function need to detect its defined type at run time and change its mode of operation. Is there any decent solutions to do this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <class T> class MyClass {
...
  T multiply(T in) {
// return a constant multiple of in.
  };
}

int main() {
MyClass<int> a;
MyClass< vector<int> > b;

int c = a.multiply(1); // simple scalar multiplication
vector<int> d = b.multiply(vector<int>(2,1)); // output should be 'element-wise' multiplication
}
closed account (2AoiNwbp)
I guess you'd probably do multiplication for each element of a vector, whereas a single object could be a vector of size one and return.
Topic archived. No new replies allowed.