-
Template problem (maybe)
Hi
maybe the solution would be using templates,and I just forgot how to use them, but right now I have the following problem:
I want to write a set of functions, so I can operate on vector<int>s as if they were integers, meaning addition, subtraction, comparing, dividing etc. But to be flexible (i.e. if one of the two or both provided integer arguments fit in 2^32-1, like loop variables), I want to allow for any mix of vectors and integers in all of the function arguments.
example:
Code:
vector<int> add(vector<int> a, vector<int> b); //0
vector<int> add(vector<int> a, int b); //1
vector<int> add(int a, vector<int> b); //2
vector<int> add(int a, int b); //3
Basically the true INTs in functions 1-3 go to a conversion function which returns the respective vector<int>, then these are provided to function 0. Same for all other functions.
Now my question would be: Can I somehow simplify this process of converting from int to vector<int> and calling the correct function, other than by overloading?
-
If you were to use templates, I would imagine the code within the function resembling a state machine that checks which template was used. I have found that having complex templates pays off most when you have several levels of inheritence. That's just my humble input.
-
>Can I somehow simplify this process of converting from int to vector<int> and calling the correct function, other than by overloading?
Yes, create an integer type that does it for you:
Code:
class Integer {
public:
Integer(int init);
Integer(vector<int> init);
...
};
Integer add(const Integer& a, const Integer& b);
Conveniently enough, this approach gives you more power than they way you were going about it. You can make the Integer class as complex or as simple as you like while protecting client code from the complexity.