Template argument invalid - Trying to use it as a vector type

I'm getting a stupid little error and I'm pretty lost to where I'm going wrong.
When I try to compile my code it says: Template argument 1 is invalid
Template argument 2 is invalid
Refering to the "type" template I declared.

Am I declaring it wrong or am I just totally blind and missing something obvious?
Because if I just change the "type" template that I made with, say, int,
it works fine.


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
41
42
43
44
45
46
47
#include <iostream>
#include <vector>

template <typename type>
void fillvector( std::vector<type>& v );
void displayvector( std::vector<type>& v );

int main()
{
	
	std::vector<int> myvector;
	fillvector( myvector );
	displayvector( myvector );
	
	return 0;
	
}

void fillvector( std::vector<type>& v )
{
	
	int n = 0;
	int i = 1;
	while( n != -1 )
	{

		std::cout << "Enter element number " << i << ": ";
		std::cin >> n;
		v.push_back( n );
		i++;
		
	}
	
	std::cout << "\n";
}

void displayvector( std::vector<type>& v)
{
	std::cout << "Vector: ";
	
	for( size_t i = 0; i < v.size(); i++ )
	{
		std::cout << v.at( i ) << " ";
	}
	
	std::cout << "\n";
}
Last edited on
displayvector is also a templated function (it uses "type").
And templates need to be fully visible (including their implementation) at the point of use since they are instantiated at compile time.
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
#include <iostream>
#include <vector>

template <typename T>
void fillvector( std::vector<T>& v ) {
	T n = 0;
	int i = 0;
	while( n != -1 ) {
		std::cout << "Enter element number " << ++i << ": ";
		std::cin >> n;
		if (n != -1)
			v.push_back( n );
	}
	std::cout << "\n";
}

template <typename T>
void displayvector( std::vector<T>& v) {
	std::cout << "Vector: ";
	for( size_t i = 0; i < v.size(); i++ )
		std::cout << v.at( i ) << " ";
	std::cout << "\n";
}

int main() {
	std::vector<int> myvector;
	fillvector( myvector );
	displayvector( myvector );
	return 0;
}

Last edited on
Ooooh I see, I got it now
So does that make the functions inline in this case?
Thanks again tpb
Last edited on
The actual functions generated from the templates will not necessarily be inlined. It's just that the source text needs to be visible at compile time to generate the actual function(s) requested. There are whole C++ libraries that are header only because they consist only of templates. Most of boost is just headers. https://www.boost.org/
Got you man. Thank you once again!..
Topic archived. No new replies allowed.