I have a Visual Studio 2008 C++03 application where I would like to have a single function perform string operations with different parameters depending on the type of string passed in.
For example, if I wanted to (naively) find the path portion of a file name with something like this:
template< typename Elem, typename Traits, typename Alloc >
std::basic_string< Elem, Traits, Alloc > GetFilePath(
const std::basic_string< Elem, Traits, Alloc >& filename )
{
std::basic_string< Elem, Traits, Alloc >::size_type slash =
filename.find_last_of( "\\/" ) + 1;
return filename.substr( 0, slash );
}
for wchar_t based strings, it would use L"\\/" and for char based strings "\\/".
And the calling convention would be something like this:
std::wstring pathW = GetFilePath( L"/Foo/Bar/Baz.txt" );
std::string pathA = GetFilePath( "/Foo/Bar/Baz.txt" );
Can anybody suggest how to modify the above function for this goal? (Yes, I realize I could have two functions that overload the GetFilePath name. I would like to avoid that, if possible.)
Create a traits class for the path separator and whatever else you’re interested in:
Then in your function template you can use
find_last_of(PathTraits<Elem>::separator).