c++if的初始化变量

#include <iostream>
constexpr int d=100;
int g(int i){return i * 2;}
int main(){
    if (auto r=g(0);r!= 0){
        std::cout<<r<<std::endl;
    }else{
        r=d;std::cout <<"结果="<<r<< std::endl;
    }//主要目的,是为了将变量局限在一定范围
}//r在判断块外就没了.同时,

//============
if (std::lock_guard lg{collMutex}; !coll.empty())//注意std::lock_guard不需要指定模板类型std::mutex了
{
    std::cout << coll.front() << '\n';
}
//等价于==下面这段

{//这一对大括号是为了说明lg变量的有效范围
    std::lock_guard<std::mutex> lg{collMutex};
    if (!coll.empty()){
        std::cout << coll.front() << '\n';
    }//就是限制了有些变量的作用范围
}//switch,同理

c++using扩展,值得一看
占位符类型作为模板参数
串作为模板参数
预处理条件__has_include
模板参数类型推导
单参静断
更方便了,比如,你可以这样:


template<auto v>
struct constant
{
static constexpr auto value = v;
};
using i = constant<42>;
using c = constant<'x'>;
using b = constant<true>;
可以这样:

template<auto... Elements>
struct sequence {
};
using indexes = sequence<0, 3, 4>;

csdn现在处理md,代码后要出问题.

发布了346 篇原创文章 · 获赞 25 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/fqbqrr/article/details/104125469
今日推荐