is there any way to force functions to only take in vectors of integers (int, unsigned int, uint32_t, etc.) and only those? im trying to write a simple function that returns the sum of all the values with the same return type (since i cant be sure whether or not the value will be greater than (2^32 - 1). however, since std::vector<T> doesnt have a cout operator for the entire type, i cannot do sum(vector<vector<T> >), since it will return a vector (ignoring the fact that vector + vector doesnt work). i do not wish to overload every type to cout something because i wont be needing it. i just want the function to work when T is some form of an int (and float if possible)
ive tried using try/except, but codeblocks catches the operators of the types, so i cant compile if i do a sum(vector <vector <T> >)
template <typename T>
T sum(std::vector <T> in){
try{
T total = 0;
for(int x = 0; x < in.size(); x++)
total += in[x];
return total;
}
catch (int e){
std::cout << "Error " << e << " has occured." << std::endl;
exit(e);
}
}
Tis an integral type, it is impossible that anintis thrown in your code.sum()template is instantiated for a type for whichT total = 0is invalid, then you'll get a compiler error. The situation is never allowed to linger and manifest at run-time, which is when exceptions and try/catch blocks execute. C++ doesn't do compilation at run-time. Separately, taking your input vector byconstreference prevents a temporary copy of the entire container being generated every time the function is called... Gene illustrates this but doesn't explain or justify it.