2

我有一个 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"\\/"and 用于基于 char 的字符串"\\/"

调用约定是这样的:

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

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

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

4

1 回答 1

1

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

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).

于 2012-07-31T20:16:43.983 回答