So you want a computer algebra system? There's a few libraries that do that. This is the first one for C++ that shows up on Google: https://www.ginac.de/
Search this forum for "rational" and "fraction." There are dozens of examples, although I don't know if many use a template, most just use an integer for numerator and denominator.