K
KK
Hello all,
I have several classes binded by one common interface - say 'sum'
interface which calculates the sum of all the class elements of type
'int'.
class Alphabet
{
int _a;
int _b;
int _c;
char _ch; // some other stray element
friend double sumInterface( int first, ... );
public:
double _sum; // ' double' type introduced to differentiate from above
core elements
Alphabet( void)
{
_a=_b=_c=2;
_sum=sumInterface(_a,_b,_c,-1);
}
};
class Numbers
{
int _one;
int _two;
friend double sumInterface( int first, ... );
public:
double _sum;
Numbers(void)
{
_one=1;
_two=2;
_sum=sumInterface(_one,_two,-1);
}
};
double sumInterface( int first, ... )
{
int i = first;
double sum=0;
va_list marker;
va_start( marker, first ); /* Initialize variable arguments. */
while( i != -1 ) //-1 acts as delimiter
{
sum += i;
i = va_arg( marker, int);
}
va_end( marker ); /* Reset variable arguments. */
return sum ;
}
The problem with this approach is that I need to provide all the class
elements to this function each type I invoke it.
_sum=sumInterface(_a,_b,_c,-1);
_sum=sumInterface(_one,_two,-1);
Is there anyway I make the function to understand to consider all the
class elements of type int so that I dont have to explicitly type all
the elements?
If yes, can I general this concept to other user defined data types?
Also, little off topic but is there a way I can avoid using a delimiter
in the variable length arguments ?
Thank you.
-KK
I have several classes binded by one common interface - say 'sum'
interface which calculates the sum of all the class elements of type
'int'.
class Alphabet
{
int _a;
int _b;
int _c;
char _ch; // some other stray element
friend double sumInterface( int first, ... );
public:
double _sum; // ' double' type introduced to differentiate from above
core elements
Alphabet( void)
{
_a=_b=_c=2;
_sum=sumInterface(_a,_b,_c,-1);
}
};
class Numbers
{
int _one;
int _two;
friend double sumInterface( int first, ... );
public:
double _sum;
Numbers(void)
{
_one=1;
_two=2;
_sum=sumInterface(_one,_two,-1);
}
};
double sumInterface( int first, ... )
{
int i = first;
double sum=0;
va_list marker;
va_start( marker, first ); /* Initialize variable arguments. */
while( i != -1 ) //-1 acts as delimiter
{
sum += i;
i = va_arg( marker, int);
}
va_end( marker ); /* Reset variable arguments. */
return sum ;
}
The problem with this approach is that I need to provide all the class
elements to this function each type I invoke it.
_sum=sumInterface(_a,_b,_c,-1);
_sum=sumInterface(_one,_two,-1);
Is there anyway I make the function to understand to consider all the
class elements of type int so that I dont have to explicitly type all
the elements?
If yes, can I general this concept to other user defined data types?
Also, little off topic but is there a way I can avoid using a delimiter
in the variable length arguments ?
Thank you.
-KK