4 ms·
template <class ttype> ttype multiply(ttype a, ttype b) { return a * b; } int * int doesn't always fit in an int. C++ Templates: The Definitive Guide
by DCoder 15y ago
template <class ttype>
ttype multiply(ttype a, ttype b)
{
return a * b;
}
int * int doesn't always fit in an int. C++ Templates: The Definitive Guide suggests using a traits class to solve problems like this. Templates are a complex subject in general, and I wouldn't recommend using them without having read the aforementioned book.
- bermanoid 15y agoint int doesn't always fit in an int.* And yet every programming language that I can think of returns an int when you multiply two ints, and we get along (mostly) just fine. Did you have a better option in mind for that bit of code?
- DCoder 15y agox86 assembler doesn't. I mentioned C+++ Templates: The Complete Guide - it demonstrates a similar template (15.2.4) to add two values, and even with simple addition it points out a flaw similar to this one (and admittedly more likely to come up in the real world) - determining the return type for, say, int + char. Their solution is a traits class with a specialization for each pair of types. Sounds complicated, but then again, so is writing a template function to perform simple multiplication.