Thread: Conditional Variable Declaring

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    1

    Conditional Variable Declaring

    I'm trying to get a function to accept several types of data (int float, char, etc) and preform the same function on them.
    I'm overloading the function by using functions that accept different types and call the main function with the type.
    Code:
    float mmmm(void* array, int size, int type);
    
    float avg(int* array, int size)
      {return mmmm(array, size, 1);}
    
    float avg(long* array, int size)
      {return mmmm(array, size, 2);}
    
    float avg(float* array, int size)
      {return mmmm(array, size, 3);}
    //etc.
    My main function then asignes a pointer to the pointer it has just been given and works with the data.
    Code:
    float mmmm(void* array, int size, int type)  {
      void* ptr = NULL;
    
       switch (type) {
    
          case 1:
            ptr = new int*;
            *ptr = (int*)array;
            break;
    
          case 2:
            ptr = new long*;
            *ptr = (long*)array;
           break;
    
         case 3:
            ptr = new float*;
            *ptr = (float*)array;
           break;
    //etc.
    Then to work with the data I use indirrection twice
    This fragment adds the sum of the data in the array
    Code:
    long double sum;
    
      for(int i = 0; i < size; i++)
         sum += *(*ptr + i);
    Why won't the compiler compile this?
    How can I get a function to accept several types of data without writing out many copies of it?

  2. #2
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    I think you want a template function.

    Something like:
    Code:
     template<typename T>
     T avg(T arr[], size_t size)
     {
    	T sum;
    
    	for(int i = 0; i < size; i++)
    		sum += arr[i];
    
    	return sum;
     }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to put a check on an extern variable set as flag
    By rebelsoul in forum C Programming
    Replies: 18
    Last Post: 05-25-2009, 03:13 AM
  2. C variable
    By webstarsandeep in forum C Programming
    Replies: 1
    Last Post: 10-23-2008, 01:26 AM
  3. Static Local Variable vs. Global Variable
    By arpsmack in forum C Programming
    Replies: 7
    Last Post: 08-21-2008, 03:35 AM
  4. variable being reset
    By FoodDude in forum C++ Programming
    Replies: 1
    Last Post: 09-15-2005, 12:30 PM
  5. Declaring an variable number of variables
    By Decrypt in forum C++ Programming
    Replies: 8
    Last Post: 02-27-2005, 04:46 PM