Search code examples
c#c++generic-method

Generic Method in C++


I would like to create a method that will do the same actions for some types of argument.

For example: I have a file and would like the method WriteToFile() to write string or a int or a double to the document.

WriteToFile( type content)
{
streamFile.open ("path\to\file.txt", fstream::in | fstream::out| fstream::app);
streamFile<<content;
}

In C# I use the T, is it possible to implement it using C++?


Solution

  • There are templates in C++ which allow you to do same logic for a different types:

    template < typename T>
    void WriteToFile( T content, File& streamFile)
    {
        streamFile.open ( "path\to\file.txt", fstream::in
                                    | fstream::out| fstream::app);
        streamFile << content;
    }
    

    That is you can create a family of functions.