Odd that you pick this example, since std::replace() (the fully generic version) would actually do what you're talking about. So this is an instance of a class simply not doing what you want it to do, not some disadvantage to generics.
To do Elysia justice, I don't think std::replace can do that (replacing substring for string), it can replace a character for another character. However, boost's string algorithms can do that and much more (alas, with free functions).
I expect a replace function to seek and replace every instance of X with Y, but that's not what std::string::replace does and it frustrates me because these classes never work in a way I expect and need.
But what if I actually want to replace a range for another?
As to the original question, can't you do something like this?
Code:
#include <iostream>
template <class T>
void convert(T n, T& m)
{
std::cout << "no conversion really\n";
m = n;
}
void convert( int n, float& f)
{
std::cout << "converting int into float\n";
f = n;
}
void convert( float n, int& i)
{
std::cout << "converting float into int\n";
i = static_cast<int>(n);
}
template <class T>
struct Number
{
T value;
Number(T t): value(t) {}
Number<int> to_int() const { Number<int> n(0); convert(value, n.value); return n; }
Number<float> to_float() const { Number<float> f(0.0); convert(value, f.value); return f; }
};
int main()
{
Number<int> n1(10), n2(12);
Number<float> f1(1.1), f2(2.2);
n1 = n2.to_int();
n2 = f1.to_int();
f1 = f2.to_float();
f2 = n2.to_float();
}