Hi,
I have a vector class vec. Now, I am creating custom utility functions using function templates. For example,
1 2 3 4 5 6 7 8 9
template <class T>
T sum(vec<T> &v) {
// calculate th sum of vector and return the value
}
template <class T>
vec<T> & find(vec<T>& v, constint val) {
// find all values where v[i] == val and return in vector
}
Here I have 2 questions.
1) when I try to call these functions in a chain fashion (last part of the code below),
1 2 3 4 5 6 7 8 9 10 11 12 13
// create sample vector
int a[5] = {1,2,5,4,5};
vec<int> v(a,5);
// code that works
vec<int> v_find = find(v, 5);
int s = sum(v_find);
// code that results in error
// error: no matching function for call to ‘sum(vec<int>)’
// note: candidates are: T sum(vec<T>&) [with T = int]
int s = sum(find(v,5));
I see that the problem is because of the difference in the function definition, I obtain the address of input object in the functions and here, I pass by value. I don't want to change at the function implementation. In that case, how do you suggest I can implement this line directly without error?
2) How can I limit this sum function template to operate only on int, float, double data types alone (without writing 3 different functions of course)?
1) I am sorry that was a typo. The function definition is,
1 2 3 4
template <class T>
vec<T> find(vec<T>& v, constint val) {
// find all values where v[i] == val and return in vector
}
But still I get the error. I suppose its because the input argument to sum() is passed by reference? And I don't want to change this.
2) Well, apart from that fact that, it was just a matter of knowing, it could be used to limit from being used against char or if a specific function shouldn't operate on bool etc... Its done using #ifndef ?
1. I would assume the error is because you're dereferencing v, and v isn't a pointer.
2. Why would you make that restriction? There's no use in it -- I mean, theoretically I could do bool b = (bool)std::cin.get(); but I wouldn't because that would be stupid. The compiler would probably let me; but it would be detrimental to my program. Ultimately, I wouldn't want to do it. Compile errors are only there because the compiler doesn't know what to do with the code you gave it. The compiler generates a warning when you do something that could be detrimental to your program.