0

I need to find all the possible, at least three, errors from the following.

template<typename A, typename B, typename C>
C myfunction(const A& a, const B& b)
{ 
   if ( a < b )  return (C) a;
   else return (C) b;
}

My answer was

  1. typename A and B can have different types that make errors, even worse the operator < is not defined in the function.

  2. typename C can be different than A and B, then it makes changes onto a, b objects which are defined const

  3. typename A can be integer type but we do not use constant reference for integer type, we only use it for objects.

My third answer was wrong....

Could anybody explain why my answers were wrong and all the possible errors that can occur from this template? I got the credit for the first two answers but I do not really like them. Anybody has better solutions for this?

Thanks,

  • Doing a cast from 'A' or 'B' to 'C' is not guaranteed to work depending on the types. 'A' and 'B' will need conversion constructors in order to work correctly if the types incompatible. – Captain Obvlious Apr 26 '13 at 00:59
  • Honestly, the worst thing I see there is probably the C-style cast, at least depending on how you intend it to work. – chris Apr 26 '13 at 01:01
  • A and B possibly do not have copy constructors defined, so you could just be returning shallow copies of a or b depending on the outcome of the if-statement (it seems like a returned reference might have been intended). This could be an error if the A and B classes have members that require a deep copy constructor. Also, the necessary constructors of A and B might not be accessible to make copies of the objects at all (compile-time error). Then again, who knows what a "myfunction" is supposed to do to begin with, so I would say a non-descriptive name is also prone to misuse of the function. – statueuphemism Apr 26 '13 at 01:09

1 Answers1

1

A cast from A to C or B to C either needs to be polymorphic or a compatible type. You may use const with an integer reference.