[ACCEPTED]-How to take a typename as a parameter in a function? (C++)-function-parameter

Accepted answer
Score: 14

To use the name of a type as a parameter, use 7 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 6 default constructible. If it is not, I guess 5 you would have difficulty streaming it out 4 of a file anyway.

Call it like this:

char value=FileRead<char>(file, pos);

If you 3 do not want to have to specify the type 2 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 1 call it like this - the type is inferred:

char value;
FileRead(file, pos, value);
Score: 4

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

0

Score: 0

I know this post is answered, but still, I 3 had a problem with that and I found a simple 2 way from this page answers. You can pass 1 type name to any function like this:

template<typename T>
void function_name()
{
    //you can access your type here with T
    //you can create an object from T or anything you want
    //for example :

    T obj;

    //or:

    T obj=new T;

}

int main(){
    function_name<YourTypeName>();
}

More Related questions