小编LHL*_*ini的帖子

基于范围的for循环中&和&&之间有什么区别?

我想知道在这个代码中for (auto& i : v),for (auto&& i : v)在基于范围的for循环之间有什么区别:

#include <iostream>
#include <vector>

int main() 
{
    std::vector<int> v = {0, 1, 2, 3, 4, 5};

    std::cout << "Initial values: ";

    for (auto i : v)    // Prints the initial values
        std::cout << i << ' ';
    std::cout << '\n';

    for (auto i : v)    // Doesn't modify v because i is a copy of each value
        std::cout << ++i << ' ';
    std::cout << '\n';

    for …
Run Code Online (Sandbox Code Playgroud)

c++ for-loop reference rvalue-reference

11
推荐指数
1
解决办法
2455
查看次数

constexpr 上下文中任何类内的 std::string 的 std::variant 无法编译

下面的代码

#include <optional>
#include <string>
#include <variant>

constexpr bool USE_VARIANT = 1;

using T = std::conditional_t<USE_VARIANT, std::variant<std::string>, std::string>;

struct S
{
    T t;
};

constexpr int func()
{
    S s{"str"};
    return 0;
}

constexpr int x = func();

int main()
{
}
Run Code Online (Sandbox Code Playgroud)

无法使用 GCC trunk(编译器资源管理器链接)进行编译,并显示以下消息

In file included from <source>:4:
<source>:21:23:   in 'constexpr' expansion of 'func()'
<source>:19:1:   in 'constexpr' expansion of '(& s)->S::~S()'
<source>:10:8:   in 'constexpr' expansion of '((S*)this)->S::t.std::variant<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::~variant()'
/opt/compiler-explorer/gcc-trunk-20211231/include/c++/12.0.0/variant:1408:28:   in 'constexpr' expansion of '((std::variant<std::__cxx11::basic_string<char, …
Run Code Online (Sandbox Code Playgroud)

c++ gcc constexpr c++20 std-variant

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

在 Bash 中混合间接扩展和参数转换时的奇怪行为

根据这个答案,我可以检查数组是否是索引的或关联的,如下所示:

$ declare -a a
$ declare -A b
$ echo ${a@a}
a
$ echo ${b@a}
A
Run Code Online (Sandbox Code Playgroud)

然而,如果我使用间接扩展,它就不起作用:

$ var=a
$ echo ${!var@a}

$ var=b
$ echo ${!var@a}

$
Run Code Online (Sandbox Code Playgroud)

然而,如果我初始化数组,它现在又可以工作了:

$ a=()
$ b=()
$ var=a
$ echo ${!var@a}
a
$ var=b
$ echo ${!var@a}
A
$
Run Code Online (Sandbox Code Playgroud)

这是预期行为还是 Bash 错误?

$ bash --version
GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)
[...]
Run Code Online (Sandbox Code Playgroud)

bash indirection

5
推荐指数
0
解决办法
69
查看次数

接收具有不可复制成员变量和按值显式声明的析构函数的类的函数转换为 std::function 失败

注意:这是这个类似问题的变体,但具有可移动对象和显式声明的析构函数。

下面的代码

#include <functional>
#include <memory>

struct S
{
    ~S();
    std::unique_ptr<int> x;
};

std::function<void(S)> x = [](S){};
Run Code Online (Sandbox Code Playgroud)

编译失败:

<source>:11:28: error: conversion from '<lambda(S)>' to non-scalar type 'std::function<void(S)>' requested
   11 | std::function<void(S)> x = [](S){};
      |
Run Code Online (Sandbox Code Playgroud)

如果我执行以下任一操作,它会按预期编译:

  1. 删除显式析构函数声明
  2. 删除x成员变量;
  3. 使用const S&而不是S.

为什么会这样?为什么明确声明很~S重要?

c++ stl

2
推荐指数
1
解决办法
46
查看次数