Thread: How to avoid template ambiguity

  1. #1

    How to avoid template ambiguity

    How do you avoid template ambiguity when working with templates and the class keyword. consider this example where the templated item is ambiguous (I assume) because non-number values can be passed into the function that accepts the templated item.

    #include <iostream>
    #include <conio.h>
    using namespace std;
    template<class X>
    long double Add(X * FirstNum, X * SecondNum);
    int main(void) {
    	float W;
    	int Z;
    	cout << "Enter a value for w " << endl;
    	cin >> W;
    	cout << "Enter a value for z " << endl;
    	cin >> Z;
    	cout << "The value of X plus Y is " << Add(&W, &Z) << endl;
    	return 0;
    template<class X>
    long double Add(X * FirstNum, X * SecondNum) {
    	long double temp = *FirstNum + *SecondNum;
    	return temp;
    However I have never actually had problems using templates whether it be with vectors or otherwise. It is just that I have never written a linked list with templates and I figured it time to do so (doesn't ever C++ programmer do that during his/her life?)

    Oh and by the way this program was written as an example so we need not comment on anything other than templates (unless I did something blatantly wrong that will make the program not compile anyway, which I don't think I did).
    Last edited by Shadow12345; 11-09-2002 at 12:03 PM.

  2. #2
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    It doesn't know whether to call

    Add(float*, float*) 
    Add(int*, int*)
    I'd suggest that you

    A. take the items by const reference, not by pointer.
    B. call the function like this

    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  3. #3
    Registered User
    Join Date
    Nov 2001
    In your example, What class template do you instantiate? I do not see a class template. I see a template function.

    Implement the template class with template functions.


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Specialising a member function with a template template parameter
    By the4thamigo_uk in forum C++ Programming
    Replies: 10
    Last Post: 10-12-2007, 04:37 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. error: template with C linkage
    By michaels-r in forum C++ Programming
    Replies: 3
    Last Post: 05-17-2006, 08:11 AM
  4. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  5. oh me oh my hash maps up the wazoo
    By DarkDays in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2001, 12:54 PM