Hi,
I want to write a function of four parameters. Each parameter can be
of type long, double or string. For example:
f(long, long, long, long);
f(long, long, long, double);
f(long, long, long, const string &);
f(long, long, double, long);
f(long, long, string, long);
f(long, long, double, double);
f(long, long, double, string);
f(long, long, string, long);
. . .
I would like write this code automaticaly. I know the next_permutation
STL algorithm, but I think that it is not useful in this case.
Any idea ?
Sounds like you're thinking in terms of applying an STL algorithm to the
process of /code generation/, as in having something create the source code
for all those functions for you, with the right adjustments for the
different parameter ordering?
I suppose it might be possible to do something in terms of writing a C++
program that uses next_permutation for something like that, but I'm not
sure that's your best solution.
When I looked at your problem, I asked myself "What does he /do/ in those
functions"? IOW, are you converting all the arguments to a single
"standard" type for use within the function? If you are, and that type is
the same across all the functions (say, double in order to be able to
represent all the possible "values" supplied as arguments, more or less),
then you can do something like this with templates:
#include <iostream>
#include <string>
#include <typeinfo>
#include <cstdlib>
using namespace std;
template<typename T>
double toDouble(const T &t)
{
cerr << "Invalid type supplied to toDouble: " <<
typeid(t).name() << endl;
return 99999.9999; // I did this as a quick-and-dirty /
// example, but it would be much better to
// do something different with compile-time
// assertions
}
template<>
inline double toDouble(const double &d) { return d; }
template<>
inline double toDouble(const long &d) { return d; }
template<>
inline double toDouble(const std::string &d)
{ return std::atof(d.c_str()); }
// and so on, for each type you wish to support...
// This version of f just returns the sum, as a double:
template<typename T1, typename T2, typename T3, typename T4>
double f(T1 v1, T2 v2, T3 v3, T4 v4)
{
return toDouble(v1) + toDouble(v2) + toDouble(v3) + toDouble(v4);
}
int main()
{
cout << f(1L,2L,3L,4L) << endl << endl;
cout << f(1.0,2L,3L,string("4.5")) << endl << endl;
cout << f(1.5,2L,3,string("4.5")) << endl << endl;
cout << f('a', 2L, 35.7, 4.3) << endl << endl;
cout << f("abc", 2L, 3.5f, 45.5) << endl << endl;
return 0;
}
Output:
10
10.5
Invalid type supplied to toDouble: int
100008
Invalid type supplied to toDouble: char
100042
Invalid type supplied to toDouble: const char *
Invalid type supplied to toDouble: float
200047
-leor