我將一組策略類放在一起,這些類對字串進行許多操作。我希望這些政策是可交換的,但“什么都不做”政策對我來說也是有問題的,因為:
- 我看不到如何避免使用移動語意進行復制,同時與姐妹策略保持相同(非移動)介面
- 編譯器應該知道對策略的呼叫可以在編譯時行內和評估,但它不接受
constexpr,因為回傳型別是字串。
#include <string>
#include<regex>
#include<cassert>
///
/// @brief Do not change anything
///
struct identity
{
static std::string edit(std::string&& s) // can not use constexpr: return type not a literal
{
return std::move(s);
}
};
///
/// @brief Template class.
///
template<unsigned int N>
struct remove_comments_of_depth
{};
///
/// @brief Do not remove anything
///
template<> struct remove_comments_of_depth<0> : identity
{};
///
/// @brief Remove all comments substrings contained between square brackets
///
/// @note Assumes that text is well formatted so there are no such things like [[]] or unclosed bracket
///
template<> struct remove_comments_of_depth<1>
{
static std::string edit(const std::string& s)
{
return std::regex_replace(s, std::regex(R"(\[[^()]*\])"), "");
}
};
int main(int argc, char *argv[])
{
std::string s = "my_string[this is a comment]";
auto copy = s;
assert(remove_comments_of_depth<1>::edit(s) == "my_string");
assert(remove_comments_of_depth<0>::edit(std::move(copy)) == s); // <<< how to avoid this call to std::move
}
在這種情況下,“標準”的方式是什么?
uj5u.com熱心網友回復:
std::move您在這里想要的是減少不必要的復制并且在呼叫時不要使用edit. 為什么不只回傳一個 const 參考?
struct identity
{
static const std::string& edit(const std::string& s) {
return s;
}
};
std::string s = "my_string[this is a comment]";
assert(remove_comments_of_depth<0>::edit("my_string[this is a comment]") == "my_string[this is a comment]");
assert(remove_comments_of_depth<0>::edit(s) == "my_string[this is a comment]");
見在線演示
至于你的第二個問題,因為 C 20,std::string可以是文字型別。
struct identity
{
constexpr static std::string edit(std::string&& s) {
return s;
}
};
static_assert(remove_comments_of_depth<0>::edit("my_string[this is a comment]") == "my_string[this is a comment]");
在 C 20 中完全沒問題,請參閱Demo。
但是由于你的變數s不能是constexpr(它是在運行時創建的),所以這里沒有太大的幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494160.html
上一篇:如果找不到,為什么IndexOf(Vb6ChrW(65533))回傳0?
下一篇:創建一個帶偏移量的字串
