I have a vector class that contains an array of type objects "T", and I want to implement 4 arithmetic operators that will apply the operation to each element:
template<class T, unsigned int D>
class Vector {
public:
void operator += (const T&) {
for (int i = 0; i < D; ++i) {
data[i] += value;
}
}
void operator -= (const T&) { ... }
void operator *= (const T&) { ... }
void operator /= (const T&) { ... }
private:
T items[D];
};
Since the operators will contain the same template code (a cycle for each element and the application of the corresponding operation), I thought I could generalize it:
template<class T, unsigned int D>
class Vector {
public:
void operator += (const T& value) { do_for_each(???, value); }
void operator -= (const T& value) { do_for_each(???, value); }
void operator *= (const T& value) { do_for_each(???, value); }
void operator /= (const T& value) { do_for_each(???, value); }
private:
void
do_for_each(std::binary_function<void, T, T>& op, T value) {
std::for_each(data, data + D, std::bind2nd(op, value));
}
T data[D];
};
Now the problem is how to pass an operator that takes two internal types and returns voidin do_for_each, as shown in the example above? C ++ does not allow me to do this trick for built-in types ( "T::operator+="will not work if "T"there is one "int").