小编Han*_*sch的帖子

基于范围的for循环on unordered_map和引用

在std :: unordered_map上运行基于范围的for循环时,似乎循环变量的类型不使用引用类型:

std::unordered_map<int, int> map = { {0, 1}, {1, 2}, {2, 3} };
for(auto&[l, r] : map)
    static_assert(std::is_same_v<decltype(r), int&>);
Run Code Online (Sandbox Code Playgroud)

MSVC 2017,gcc 8.2和clang 7.0.0都报告了一个失败的断言.将此反对到std :: vector,其中断言不会失败,正如人们所期望的那样:

std::vector<int> vec = { 1, 2, 3 };
for(auto& r : vec)
    static_assert(std::is_same_v<decltype(r), int&>);
Run Code Online (Sandbox Code Playgroud)

然而,在MSVC 2017和gcc 8.2上,修改局部变量r的循环将具有可观察到的副作用:

#include <iostream>
#include <type_traits>
#include <unordered_map>
#include <vector>

int main() {
    std::unordered_map<int, int> a = { {0, 1}, {1, 2}, {2, 3} };
    for(auto[l, r] : a)
        std::cout << l << "; " << …
Run Code Online (Sandbox Code Playgroud)

c++ unordered-map language-lawyer c++17 structured-bindings

14
推荐指数
1
解决办法
796
查看次数

如果constexpr没有丢弃在模板化的lambda中的假分支

我在模板化的lambda中遇到"if constexpr"的问题.为了论证,让我们忽略我是如何到达那里的,但我有一个结构foo,它以某种方式定义,产生如下内容:

template<bool condition>
struct foo {
    int a;

    // Only contains b if condition is true
    int b;
}
Run Code Online (Sandbox Code Playgroud)

现在我可以定义一个模板函数thtemplate

template<bool condition>
void print_fun(foo & obj) {
    /* Do something with obj.a */
    if constexpr(condition)
        /* Do something with obj.b */
};
Run Code Online (Sandbox Code Playgroud)

实例化这个功能,并使用它会编译,如果constexpr参数foo是一样的一个print_fun,即

constexpr bool no = false;
foo<no> obj = {};
print_fun<no>(obj);
Run Code Online (Sandbox Code Playgroud)

这会编译,因为假分支在模板化实体内被丢弃,因此在print_fun中使用obj.b没有问题.

但是,如果我定义一个类似的lambda表达式如下:

template<bool condition>
auto print_lambda = [](foo & obj) {
    /* Do something with obj.a */
    if constexpr(condition)
        /* Do something …
Run Code Online (Sandbox Code Playgroud)

c++ lambda templates c++17 if-constexpr

10
推荐指数
1
解决办法
796
查看次数