专业的编程技术博客社区

网站首页 > 博客文章 正文

C++20尝鲜:问题修复二(解决c++问题的软件)

baijin 2024-08-13 00:56:18 博客文章 5 ℃ 0 评论


隐式lambda捕获

#include<iostream>
#include<memory>

struct S{
    int x{1};
    int y{[&]{ return x + 1; }()};  // OK, captures 'this'
};
template<bool B>
void f1() {
    std::unique_ptr<int> p;
    [=]() {
        if constexpr (B) {
            (void)p;        // always captures p
        }
    }();
}
/*
void f2() {
    std::unique_ptr<int> p;
    [=]() {
        typeid(p);  // error, can't capture unique_ptr by-value
    }();
}
*/
void f3() {
    std::unique_ptr<int> p;
    [=]() {
        sizeof(p);  // OK, unevaluated operand
    }();
}
int main(int argc, char **argv)
{
  S s;
  //f1<false>();    // error, can't capture unique_ptr by-value
  //f2();
  f3();
    
}

默认成员初始化器中的Lambdas现在可以正式拥有捕获列表,它们的外围作用域是类作用域,其次在被丢弃的语句和typeid中,实体也会隐式地被捕获。

const与默认的复制构造函数不匹配

#include<iostream>
#include<memory>

struct NonConstCopyable{
    NonConstCopyable() = default;
    NonConstCopyable(NonConstCopyable&){}   // takes by non-const reference
    NonConstCopyable(NonConstCopyable&&){}
};

// std::tuple(const std::tuple& other) = default;   // takes by const reference

int main(int argc, char **argv)
{
    std::tuple<NonConstCopyable> t; // error in C++17, OK in C++20
    //auto t2 = t;                    // always an error
    auto t3 = std::move(t);         // OK, move-ctor is used
    
}

这个修正允许类型拥有默认的复制构造函数,该构造函数通过const引用获取参数,即使它的某些成员或基类拥有通过非const引用获取参数的复制构造函数。


当作函数模板进行参数依赖查找

#include<iostream>
#include<memory>

int h;
void g(){};

namespace N {
	struct A {};
	template<class T> int f(T){};
	template<class T> int g(T){};
	template<class T> int h(T){};
}


int main(int argc, char **argv)
{
  // OK: lookup of `f` finds nothing, `f` treated as a template name
  auto a = f<N::A>(N::A{});
  // OK: lookup of `g` finds a function, `g` treated as a template name
  auto b = g<N::A>(N::A{});
  // error: `h` is a variable, not a template function
  //auto c = h<N::A>(N::A{};
  // OK, `N::h` is qualified-id
  auto d = N::h<N::A>(N::A{});
    
}

后面有<的unqualified-id,并且名称查询没有发现或发现一个函数,将被视为一个模板名称,以便可以执行参数依赖查询ADL。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表