我有一个函数来检查是否std::string
包含子字符串.我将字符串传递给std::string_view
,因此不会发生任何复制.
bool containsSubstr(std::string_view str, std::string_view substr)
{
return str.find(substr) != std::string::npos;
}
Run Code Online (Sandbox Code Playgroud)
我现在想要使用新的C++ 17折叠表达式来创建一个函数,以检查字符串是否包含多个子字符串.再一次,我想通过std::string_view
s 传递它们.
我怎样才能做到这一点?
template<typename... Substrs>
bool containsAllSubstr(std::string_view str, Substrs... substrs)
{
return (containsSubstr(str, substrs) && ...);
}
Run Code Online (Sandbox Code Playgroud)
据我所知,上面的版本将子字符串作为它们所来自的类型.所以a std::string
将被复制.我该如何修改类型std::string_view
?就像是:
template<> // does not compile
bool containsAllSubstr(std::string_view str, std::string_view... substrs)
{
return (containsSubstr(str, substrs) && ...);
}
Run Code Online (Sandbox Code Playgroud) 我从以下网站获取了关于std :: memory_order_seq_cst的示例:http://en.cppreference.com/w/cpp/atomic/memory_order
#include <thread>
#include <atomic>
#include <cassert>
std::atomic<bool> x = {false};
std::atomic<bool> y = {false};
std::atomic<int> z = {0};
void write_x()
{
x.store(true, std::memory_order_seq_cst);
}
void write_y()
{
y.store(true, std::memory_order_seq_cst);
}
void read_x_then_y()
{
while (!x.load(std::memory_order_seq_cst))
;
if (y.load(std::memory_order_seq_cst)) {
++z;
}
}
void read_y_then_x()
{
while (!y.load(std::memory_order_seq_cst))
;
if (x.load(std::memory_order_seq_cst)) {
++z;
}
}
int main()
{
std::thread a(write_x);
std::thread b(write_y);
std::thread c(read_x_then_y);
std::thread d(read_y_then_x);
a.join(); b.join(); c.join(); d.join();
assert(z.load() != 0); // …
Run Code Online (Sandbox Code Playgroud) #include <string>
#include <iostream>
std::string(foo);
int main()
{
std::cout << foo.size() << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果0
,而不是foo
未定义的预期编译错误.
怎么能这样做?这个叫什么?