Both 7stud's and ygf's codes will work, but personally, I'd avoid both of them. Essentially what you are doing is adding type-specialized code to something which is generalized (namely, a templated class such as this).
7stud's would cause a proliferation of code (which is what templates are partially designed to avoid), and ygf's could be the cause of some very subtle errors (truncation errors from the cast operation ... which probably should have a 'static_cast' to make it clear).
Anyways, what I'd advise is a more generic solution like the following :
Code:
#include <functional>
template<typename T>
class test {
public:
T get_value() const { return value; }
template<typename A, typename Func>
void assign(test<A>, Func);
private:
T value;
};
template<typename T> template<typename A, typename Func>
void test<T>::assign(test<A> src, Func convert) {
value = convert(value, src.get_value());
}
struct convert_char : public std::binary_function<int, char, int> {
int operator()(int x, char y) { return x + static_cast<int>(y); }
};
int main() {
test<int> obj_a;
test<char> obj_b;
obj_a.assign(obj_b, convert_char());
}
The convert type in this case is a binary functor which takes the value of the object being assigned to first, and then the next parameter is the value of the second object. It is still possible to get around some of the conversion rules (i.e. poor casting practices with primitive types), but in this case, that is hard to do accidently. Also, this preserves the generic nature of the class (you aren't adding type-specialized code to it).