How to take a typename as a parameter in a function? (C++)
Solution 1
To use the name of a type as a parameter, use a template.
template<typename T>
T FileRead(std::fstream &file, int pos)
{
T data;
file.read(reinterpret_cast<char*>(&data), sizeof(T));
return data;
}
This assumes that the type is default constructible. If it is not, I guess you would have difficulty streaming it out of a file anyway.
Call it like this:
char value=FileRead<char>(file, pos);
If you do not want to have to specify the type in the call, you could modify your API:
template<typename T>
void FileRead(std::fstream &file, int pos, T &data)
{
file.read(reinterpret_cast<char*>(&data), sizeof(T));
}
Then call it like this - the type is inferred:
char value;
FileRead(file, pos, value);
Solution 2
Very simple:
template<typename T>
T FileRead(std::fstream file, int pos)
{
T data;
file.read(reinterpret_cast<char*>(&data), sizeof(data));
return data;
}
and call it via:
char x = FileRead<char>(file, pos);
Admin
Updated on June 14, 2022Comments
-
Admin almost 2 years
I need to be able to pass a typename as a parameter:
int X = FileRead(file, 9, char);
The concept is for FileRead(std::fstream, int pos, ???) to read pos*sizeof(whatever the type is) to get the desired position. I tried templates:
template<typename T> T FileRead(std::fstream file, int pos, T type) { T data; file.read(reinterpret_cast<char*>(&data), sizeof(data)); return data; }
but that required that I create a variable of the type to use every time I wanted to use FileRead, and I really don't feel like redesigning an entire program just because of one function, so is there anyway to use a typename as a parameter?
-
Abhi almost 15 yearsI think you'd need T as an argument rather than just as the return value.
-
sth almost 15 yearsCall it like FileRead<char>(file, pos);
-
Daniel A. White almost 15 yearsYou will have to call it with the template argument. codersource.net/cpp_function_template_overloading.html
-
JSBձոգչ almost 15 yearsFor readability you might want to add 'void' as the return type from FileRead().
-
1800 INFORMATION almost 15 yearsOpps heh. Not just readability, if you leave it off then the type defaults to int
-
Johannes Schaub - litb almost 15 yearsI think in this case, types that are not default constructible couldn't be passed anyway (in c++03, at least), since for those, they are not PODs anyway and using read on them would be UB (and "const T" can't be modified either). If your compiler can do that as an extension and you would like to use non-default constructible types, you can use this definition instead: template<typename T> T FileRead(std::fstream &file, int pos, T data = T()) { file.read(reinterpret_cast<char*>(&data), sizeof(T)); return data; }, which is the same technique also used by C::resize standard container functions.
-
RamblingMad about 10 yearsIf that were true RTTI wouldn't exist.