Can c++ templates only be used once?

Asked

Viewed 62 times

0

I have this code in c++ and am getting an error:

#include<iostream>
using namespace std;
template <class T>

void setVector(T* v, int sizeOfV){
for(int i=0;i<sizeOfV;i++)cin>>v[i];

}
void showVector(T* v, int sizeOfV){
for(int i=0;i<sizeOfV;i++)cout>>endl>>v[i];}

That’s the mistake right there:

T não está no escopo
V não está no escopo

Can a template only be used once??? I would like to clarify this question :D

1 answer

4

The error occurs because the compiler does not see the type T in the second function. Two functions cannot share the same generic type, you need to declare each function as template:

#include<iostream>
using namespace std;

template <class T>
void setVector(T* v, int sizeOfV) 
{
    for (int i = 0; i<sizeOfV; i++)
        cin >> v[i];
}

template <class T>
void showVector(T* v, int sizeOfV)
{
    for (int i = 0; i<sizeOfV; i++)
        cout >> endl >> v[i];
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.