Function Overloading Question C++

Status
Not open for further replies.

H-Hour

Ars Scholae Palatinae
606
ok what i want to do is to build a function that will take unspecified number of strings.

int foo("ARS IS COOL","H-HOUR IS KEWL", "NO SCRIPT KIDDIES")

ok if i were to pass it 5, 10, or 256 (or any number in between) strings how can i write the overloaded function without having to write 256 slightly differnt functions

also is there a way to get the number of strings passed to the function foo

im thinking of a char* or somthing

please let me know if this can be done and if it can how you can do it


thanks
 
You have a few options. The worst, IMO, is to use an ellipsis function. This is how printf and scanf take an arbitrary number of arguments.

Better would be to pass a single argument, which is an array of char*. The last element in the array would be a NULL pointer to indicate the end.

Best, IMO, would be to use one of the standard containers (probably vector in this case) of strings and pass that as a container or as a half open range. The latter is how all of the algorithms in the C++ standard library work.
 

H-Hour

Ars Scholae Palatinae
606
alright thanks for the ideas i will give the vector a try

not an expert on vectors but wont i have to use a vector of strings to call the function the usablity i want is like above where the user can just type in the list of strings

FYI this is so beginning c++ programmers can create menu driven console apps

[This message was edited by H-Hour on May 07, 2002 at 12:03.]
 

DrPizza

Well-known member
93,870
I don't have a compiler handy, but try something like this:
Code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;

template<typename ForwardIterator>
void foo(ForwardIterator first, ForwardIterator last)
{
    for(ForwardIterator it = first; it != last; ++it)
    {
        cout << *it << endl;
    }
}

int main(void)
{
    vector<string> v;
    v.push_back("Hello");
    v.push_back("World");
    foo(v.begin(), v.end());
    char* a[] = { "Hello", "World" };
    foo(a, a + (sizeof(a) / sizeof(*a))); // legal, pointers can point one past an array
    size_t s = 2;
    char** da = new char*[s];
    da[0] = "Hello";
    da[1] = "World";
    foo(da, da + s); // legal, pointers can point one past an array

}
etc.
 
Hmm, all those are pretty complex for such a simple problem. My suggestion is to use a 'elipsis' normally seen as '...'

(sample code below, borrowed from:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclang98/HTML/_pluslang_functions_with_variable_argument_lists.asp
)
------------------------------
#include <stdio.h>
#include <stdarg.h>

// Declaration, but not definition, of ShowVar.
int ShowVar( char *szTypes, ... );

void main()
{
ShowVar( "fcsi", 32.4f, 'a', "Test string", 4 );
}
// ShowVar takes a format string of the form
// "ifcs", where each character specifies the
// type of the argument in that position.
//
// i = int
// f = float
// c = char
// s = string (char *)
//
// Following the format specification is a list
// of n arguments, where n == strlen( szTypes ).
void ShowVar( char *szTypes, ... )
{
va_list vl;
int i;

// szTypes is the last argument specified; all
// others must be accessed using the variable-
// argument macros.
va_start( vl, szTypes );

// Step through the list.
for( i = 0; szTypes != '\0'; ++i )
{
union Printable_t
{
int i;
float f;
char c;
char *s;
} Printable;

switch( szTypes ) // Type to expect.
{
case 'i':
Printable.i = va_arg( vl, int );
printf( "%i\n", Printable.i );
break;

case 'f':
Printable.f = va_arg( vl, float );
printf( "%f\n", Printable.f );
break;

case 'c':
Printable.c = va_arg( vl, char );
printf( "%c\n", Printable.c );
break;

case 's':
Printable.s = va_arg( vl, char * );
printf( "%s\n", Printable.s );
break;

default:
break;
}
}
va_end( vl );
}
 

DrPizza

Well-known member
93,870
So this is "simple":

Code:
void ShowVar( char *szTypes, ... )
{
	va_list vl;
	int i;
	// szTypes is the last argument specified; all
	// others must be accessed using the variable-
	// argument macros.
	va_start( vl, szTypes );

	// Step through the list.
	for( i = 0; szTypes[i] != '\0'; ++i )
	{
		union Printable_t
		{
			int i;
			float f;
			char c;
			char *s;
		} Printable;

		switch( szTypes[i] ) // Type to expect.
		{
		case 'i':
			Printable.i = va_arg( vl, int );
			printf( "%i\n", Printable.i );
			break;

		case 'f':
			Printable.f = va_arg( vl, float );
			printf( "%f\n", Printable.f );
			break;

		case 'c':
			Printable.c = va_arg( vl, char );
			printf( "%c\n", Printable.c );
			break;

		case 's':
			Printable.s = va_arg( vl, char * );
			printf( "%s\n", Printable.s );
			break;

		default:
			break;
		}
	}
	va_end( vl );
}

And this is "complex":
Code:
template<typename ForwardIterator>
void foo(ForwardIterator first, ForwardIterator last)
{
	for(ForwardIterator it = first; it != last; ++it)
	{
		cout << *it << endl;
	}
}

How so?

There are obvious dangers with the varargs function (as with all varargs functions). For instance, bad things may well happen if you say <tt>showVar("s", 1234); // oops, meant to use "i"</tt> or <tt>showVar("ss", "Hello, World!"); // oops, meant to use "s"</tt>. The templated code is immune to such errors.

For this case, one would be better off writing the varargs function as taking an integer, for number of arguments, not a formatting string, as that way one only has to ensure the count and arguments match, instead of the count, the types, and the number of arguments.

Further, if one does not know at runtime whether one is passing three strings or thirty, one cannot use the varargs function in any case.

The templated range function is both simpler and more versatile. It will print anything in the range [first, last), no matter how many arguments are passed, and it makes it harder (particularly when used with a <tt>vector</tt> or some other container) to screw things up by passing in incorrect arguments. It can use any container as its input, even raw arrays of <tt>char*</tt>.
 
Status
Not open for further replies.