struct template in function template

Hello People,

I want to use a function template which returns a structure template.

The situation is as follows:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#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' 


Thanks
Last edited on
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.
Last edited on
Thanks Cubbi.

Yes, you are right, I should have used v[row].resize(columns), it was a distraction.

The code now works right with your suggested modifications.

Thank you very much for your explanation too.
Last edited on
Topic archived. No new replies allowed.