小编Arn*_*gel的帖子

如何使用特定类型的折叠表达式?

我有一个函数来检查是否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_views 传递它们.

我怎样才能做到这一点?

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)

c++ fold-expression c++17

6
推荐指数
1
解决办法
274
查看次数

std :: memory_order_seq_cst如何工作

我从以下网站获取了关于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)

c++ memory-barriers c++11

5
推荐指数
1
解决办法
671
查看次数

std :: string如何构造一个名称作为构造函数参数的对象?

#include <string>          
#include <iostream>        

std::string(foo);          

int main()                 
{                          
    std::cout << foo.size() << "\n";                                                
    return 0;              
}                          
Run Code Online (Sandbox Code Playgroud)

结果0,而不是foo未定义的预期编译错误.

怎么能这样做?这个叫什么?

c++

4
推荐指数
1
解决办法
131
查看次数

标签 统计

c++ ×3

c++11 ×1

c++17 ×1

fold-expression ×1

memory-barriers ×1