CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1

Threaded View

  1. #1
    Join Date
    Dec 2007
    Posts
    5

    [RESOLVED] Automatic type promotion with templates?

    Okay, I just found a solution using traits classes that define all of the type promotions in advance.

    Thanks
    -------------------------

    Often I have the need to code a binary function that takes basic types, (e.g., an int and a double), and I'd like the return type to automatically be the highest promoted type using c++ type promotion rules. I've given an example below. Does anyone have a solution that would return a double for both calls, without requiring me to explicitly specify the return type, or without the need for explicit template specification for every combination of types?

    Thanks in advance.

    Code:
    #include <iostream>
    
    using namespace std;
    
    // Intended to multiply basic types.
    template <typename T, typename U>
    T Multiply(T left, U right) {
    	return left * right;
    }
    
    // Generates compiler error if uncommented, since ambiguous, but we
    // really want this to be a possible function as well.
    /*
    template <typename T, typename U>
    U Multiply(T left, U right) {
    	return left * right;
    }
    */
    
    
    int main() {
    	int a = 5;
    	double b = 1.5;
            
            // Good: returns a double.
    	cout << b << " * " << a << " = " << Multiply(b,a) << endl; 
            // Bad: returns an int and truncates the result.
    	cout << a << " * " << b << " = " << Multiply(a,b) << endl; 
    
    	/* stdout:
    		1.5 * 5 = 7.5
    		5 * 1.5 = 7
    	*/
    
    	return 0;
    }
    Last edited by erikmc1; February 21st, 2008 at 09:58 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured