私が作った機能は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;
}
別の関数を作ることにしましたはい、それは吸います。 スラッシュ - >バックスラッシュは変更です。重複を取り除きたい
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;
}
私はそれらを統合しました。重複が削除されました。しかし、追加のパラメータが来た。私はまだ不快感を感じる。 重複を削除する他の方法はありませんか?たとえば、高次関数を使用します。
お願いします。あなたはテンプレートパラメータとしてchar
なくconst char*
を渡していることを見るように、
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;
}
あなたは、この目的のために、あなたのロジックビットを変更する必要があります。
これらの機能を使用する代わりに、Pathクラスを組み込む必要があります。クラスパスでは、パス文字列の妥当性に注意します。 OOの概念を使用する。 – AlexTheo
'bool backSlash = false'のデフォルト値を示します。 – atoMerz