How to take a typename as a parameter in a function? (C++)

user98188 picture user98188 · Jun 2, 2009 · Viewed 14k times · Source

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?

Answer

1800 INFORMATION picture 1800 INFORMATION · Jun 2, 2009

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);