如何删除这个简单代码中的重复?

Ben*_*min 2 c++ refactoring design-patterns code-duplication

AppendLastSlashIfNotExist我有一个功能.
今天,我决定再做一个功能AppendLastBackSlashIfNotExist

wstring AppendLastSlashIfNotExist(__in const wstring& path)
{
    if (path == L"/")
    {
        return path;
    }

    if (path.size() == 0 || path[path.size() - 1] != L'/')
    {
        return path + L"/";
    }
    return path;
}

wstring AppendLastBackSlashIfNotExist(__in const wstring& path)
{
    if (path == L"\\")
    {
        return path;
    }

    if (path.size() == 0 || path[path.size() - 1] != L'\\')
    {
        return path + L"\\";
    }
    return path;
}
Run Code Online (Sandbox Code Playgroud)

是的,很糟糕.只有Slash - > BackSlash才是变化.我想删除重复.

wstring AppendLastSlashIfNotExist(__in const wstring& path, bool backSlash)
{
    if (path == (backSlash ? L"\\" : L"/"))
    {
        return path;
    }

    if (path.size() == 0 || path[path.size() - 1] != (backSlash ? L'\\' : L'/'))
    {
        return path + (backSlash ? L"\\" : L"/");
    }
    return path;
}
Run Code Online (Sandbox Code Playgroud)

我整合了它们.删除重复.但是另外一个参数来了.我还是觉得不舒服.是否有其他方法可以删除重复?例如,通过高阶函数使用.
请问任何想法.

iam*_*ind 6

template 是这些问题的答案:

template<char SLASH_TYPE>
wstring AppendLastSlashIfNotExist(__in const wstring& path)
{
    if (path[0] == SLASH_TYPE)  // <--- comparing char (not const char*)
    {
        return path;
    }

    if (path.size() == 0 || path[path.size() - 1] != SLASH_TYPE)
    {
        return path + SLASH_TYPE;
    }
    return path;
}
Run Code Online (Sandbox Code Playgroud)

您需要为此目的稍微改变一下逻辑,因为您看到正在传递char而不是const char*模板参数.

该函数将被称为:

y = AppendLastSlashIfNotExist<'/'>(x);
y = AppendLastSlashIfNotExist<'\\'>(x);
Run Code Online (Sandbox Code Playgroud)

  • 为什么不将相关字符作为运行时参数传递?众所周知,我会用模板拍摄,但这似乎是一个太大的教规.您可能希望将此模板作为模板的唯一原因是避免在传递函数对象时绑定char. (4认同)

hmj*_*mjd 6

您可以只传递所需的斜杠字符,而不是传递布尔值来指示斜杠类型,并且可能具有斜杠字符的默认值:

wstring AppendLastSlashIfNotExist(__in const wstring& path,
                                  wchar_t slash = L'\\')
{
    // This is superfluous and is handled in next if condition.
    /*if (1 == path.length() && path[0] == slash)
    {
        return path;
    }*/

    if (path.size() == 0 || path[path.size() - 1] != slash)
    {
        return path + slash;
    }
    return path;
}

std::wstring s(L"test");
std::wcout << AppendLastSlashIfNotExist(s) << "\n";
std::wcout << AppendLastSlashIfNotExist(s, L'/') << "\n";
Run Code Online (Sandbox Code Playgroud)