#include <vector> // std::vector
template <typename T>
struct StructureTemplate
{
//...
std::vector<T> values;
//...
}; // end structure StructureTemplate
template <typename T, typename V>
StructureTemplate<T> FunctionTemplate(std::vector<std::vector<V>> v)
{
StructureTemplate<T> output;
//...
return output;
} // end template FunctionTemplate
int main ()
{
int rows = 3;
int columns = 4;
std::vector<std::vector<int>> v;
v.resize(rows);
for ( int row = 0; row < rows; row++ ) {
v.resize(columns);
for ( int column = 0; column < columns; column++ ) {
v[row][column] = rand() % 2;
}
}
StructureTemplate<double> S;
S = FunctionTemplate(v);
}
I don't know what is the problem with this code.
It is giving the following error message:
In function 'int main()':
49:23: error: no matching function for call to 'FunctionTemplate(std::vector<std::vector<int> >&)'
49:23: note: candidate is: 14:22: note: template<class T, class V> StructureTemplate<T> FunctionTemplate(std::vector<std::vector<V> >)
14:22: note: template argument deduction/substitution failed:
49:23: note: couldn't deduce template parameter 'T'
as it said "couldn't deduce template parameter 'T' ".
It can figure out V from the argument: the argument is std::vector<std::vector<int>>, the parameter is std::vector<std::vector<V>>, therefore V = int, but it has no information to deduce T from.
The fact that you plan on using the result of this function on the right hand side of an assignment operator whose left hand side has type StructureTemplate<double> is not applicable: type deduction isn't going to examine your whole program. It goes from arguments to parameters, not the other way around.
This will work. S = FunctionTemplate<double>(v);
If you're concerned with repeating yourself, skip default-constructing the S and deduce it right here: auto S = FunctionTemplate<double>(v);
(also, once compiled, your program will crash because after v.resize(columns); you have a vector of 4 empty vectors, and v[0][0] does not yet exist.