创建一个字符宽度不可知的功能

时间:2012-07-31 20:08:42

标签: c++

我有一个Visual Studio 2008 C ++ 03应用程序,我想让一个函数根据传入的字符串类型执行不同参数的字符串操作。

例如,如果我想(天真地)找到文件名的路径部分,如下所示:

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 );
}

对于基于wchar_t的字符串,它将使用L"\\/"和基于字符的字符串"\\/"

调用约定是这样的:

std::wstring pathW = GetFilePath( L"/Foo/Bar/Baz.txt" );

std::string pathA = GetFilePath( "/Foo/Bar/Baz.txt" );

有人可以建议如何为此目标修改上述功能吗? (是的,我意识到我可能有两个重载GetFilePath名称的函数。如果可能的话,我想避免这种情况。)

1 个答案:

答案 0 :(得分:1)

为路径分隔符和您感兴趣的任何其他内容创建一个traits类:

template<typename Elem> struct PathTraits { static const Elem *separator; };
template<> const char *PathTraits<char>::separator = "\\/";
template<> const wchar_t *PathTraits<wchar_t>::separator = L"\\/";

然后在您的功能模板中,您可以使用find_last_of(PathTraits<Elem>::separator)