Reputation: 23
I'm Trying to make a template function and pass two variables to it by reference , every thing sounds good but it never compiled and the error message is :-
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
I tried a small part of code and it gives me same error, any help please??
And this a part of code, the all other code is just like this:
int size , found = -1 ;
template<class type> Read_Data( type &key , type &arr)
{
cout << " please enter the size of your set \n " ;
cin >> size ;
arr = new type[size];
cout << " please enter the elements of your set : \n " ;
for (int i = 0 ; i <size ; i ++ )
{
cout << " enter element number " << i << ": " ;
cin >> arr[i] ;
}
cout << " please enter the key elemente you want to search for : \n " ;
cin >> key ;
}
void main(void)
{
int key , arr ;
Read_Data (key, arr);
/*after these function there is two other functions one to search for key
in array "arr" and other to print the key on the screen */
}
Upvotes: 2
Views: 10731
Reputation: 206
You are just missing a couple of things to get the code compiling (resolving the error you saw).
Basically, in int main()
, you need to specify the type when instantiating the template, as in:
Read_Data <int> (key, value);
so that the compiler knows what type you really want to instantiate it with.
Also note that the array should be of type int *
. So in the templated function the signature has to change to:
template<class type> Read_Data( type &key , type* &arr)
This is the corrected code which won't show the error you were previously seeing:
#include<iostream>
using namespace std;
int size , found = -1 ;
template<class type> void Read_Data( type &key , type* &arr)
{
cout << " please enter the size of your set \n " ;
cin >> size ;
arr = new type[size];
cout << " please enter the elements of your set : \n " ;
for (int i = 0 ; i <size ; i ++ )
{
cout << " enter element number " << i << ": " ;
cin >> arr[i] ;
}
cout << " please enter the key elemente you want to search for : \n " ;
cin >> key;
}
int main()
{
int key;
int * arr;
Read_Data<int> (key, arr);
/* after these function there is two other functions one to search for key
* in array "arr" and other to print the key on the screen
*/
}
Upvotes: 1
Reputation: 30136
You need to specify a return-value type in the declaration of function Read_Data
.
A few examples:
template<class type> void Read_Data( type &key , type &arr)
template<class type> int Read_Data( type &key , type &arr)
template<class type> type Read_Data( type &key , type &arr)
The first example is probably what you need if you're not planning to return anything in that function...
BTW, you also need to:
main
, change int arr
to int* arr
.main
, change Read_Data
to Read_Data<int>
.main
, call delete[] arr
after you finish using it.Read_Data
, change type &arr
to type* &arr
.Upvotes: 1