I'm working on a section of code that allows the user to search by different types ( double
/ string
/ date
(custom class)). This involves a method called readInSearchCriteria()
that I have tried to set as a template. I have done some research into template functions and here is what I have so far:
//template function to process different datatypes
template <typename T> UserInterface::readInSearchCriteria() const {
//template instance to hold data input from keyboard
T t;
//prompt user to enter a value
cout << "\n ENTER SEARCH CRITERIA: ";
//read-in value assigned to template variable
cin >> t;
//return initialised template variable
return t;
}
I have called this at one point in the program to process a double
like so:
double amount = theUI_.readInSearchCriteria<double>(); //works absolutely fine
However, when I tried to call it on a string
, I was given the following error by the compiler:
no suitable constructor exists to convert from "int" to "std::basic_string, std::allocator>"
Would anyone be able to offer me any advice on what might be going wrong here?
You have a typo in your function declaration: you're not specifying a return type, so the compiler is defaulting to int
.
You need to add T
as the return type:
template <typename T>
T UserInterface::readInSearchCriteria() const {
...
return T
}
The method readInSearchCriteria
doesn't have a return type. You have to specify the return type for a function, here it is implicit int
because you haven't specified one.
template <typename T> T UserInterface::readInSearchCriteria() const;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.