How to create a C++ function that can take argment of both char* and wchar_t*

Source.
Create a traits class that is used as specialized template. Specialize it for char and wchar_t. Generic template is not defined because this function is only for char and wchar_t.

#include <wchar.h>
#include <stdio.h>
 
template<typename T> struct kansuu_traits;
template<> struct kansuu_traits<char>
{
	static FILE* open(const char* p)
	{
		return fopen(p, "r");
	}
};
template<> struct kansuu_traits<wchar_t>
{
	static FILE* open(const wchar_t* p)
	{
		return _wfopen(p, L"r");
	}
};
 
template<typename cT> void kansuu(const cT* p)
{
	FILE* f = kansuu_traits<cT>::open(p);
	fclose(f);
}
 
int main(int argc, char* argv[]){
	kansuu(L"C:\\TEST\\Text.txt");
	kansuu("C:\\TEST\\Text.txt");
 
	return 0;
}

Leave a comment

Your email address will not be published. Required fields are marked *