I've been toying around with a multitude of topics including function templates, exceptions, making use of files, and in turn, using a static variable for a specific function. I've noticed that it doesn't maintain it's value:
#include <iostream>
#include <fstream>
#include <string>
/*This function will take ofstream and ifstream
as arguments and see if the file is open*/
template<typename T>
bool is_openCheck(T& a)
{
staticint n = 0;
n++;
std::cout << "n is equal to " << n << std::endl; /*This is to show that n isn't
maintaining its value throughout*/
try
{
if (!a.is_open())
{
throw 1;
}
}
catch(int x)
{
std::cout << "Error code " << x << ": File number " << n << " not found" << std::endl;
std::cout << "Critical error, program will close" << std::endl;
system("pause");
returnfalse;
}
returntrue;
}
int main()
{
std::ofstream openFile("test.txt", std::ios::in);
std::ofstream openFile2("test2.txt", std::ios::in);
std::ifstream openFile3("test3.txt");
if ( (is_openCheck<std::ofstream>(openFile)) == false)
{
return -1;
}
if ( (is_openCheck<std::ofstream>(openFile2)) == false)
{
return -1;
}
if ( (is_openCheck<std::ifstream>(openFile3)) == false)
{
return -1;
}
system("pause");
return 0;
}
The console window will proceed to output:
n is equal to 1
n is equal to 2
n is equal to 1
Press any key to continue . . .
It works fine until up until the third line of output, where I'd expect it to say "n is equal to 3".
Does it re-initialize n because the argument being taken is of different type than the previous two times the function was called? And if not, then what is wrong, and is there a way to adjust the code in order for it to work according to my expectations?