1

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++?

user3165438
  • 2,631
  • 7
  • 34
  • 54

1 Answers1

1

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.

4pie0
  • 29,204
  • 9
  • 82
  • 118
  • Thanks, Where should I define this class? What is its content? – user3165438 Aug 24 '14 at 12:30
  • in the example WriteToFile is a method and should be declared in header and implemented in cpp file – 4pie0 Aug 24 '14 at 12:38
  • What is it ? an internal class? – user3165438 Aug 24 '14 at 12:39
  • T is template parameter, a variable that represents many possible variables, read about the [templates](http://en.wikipedia.org/wiki/Template_(C%2B%2B)) in C++ – 4pie0 Aug 24 '14 at 12:39
  • Thanks, I tried it and it works fine. One more thing: why should I locate the template line at the line above the method? Can I move it to another place? – user3165438 Aug 24 '14 at 12:48
  • no, this is to inform compiler that this what appears to be under this line is a template – 4pie0 Aug 24 '14 at 12:50
  • It is better to use template because T does not necessarily have to be a class. This is just meant as positive criticism, the answer is correct. – Philip Stuyck Aug 24 '14 at 15:50
  • yeah, however let me notice that there is absolutely no technical difference between these two, both 'class' & 'typename' can be used with very same types – 4pie0 Aug 24 '14 at 15:59
  • Correct I was not suggesting otherwise. But the point really is that the keyword typename is better documenting the intent of the code. – Philip Stuyck Aug 24 '14 at 16:51