蓝桥ROS机器人之现代C++学习笔记2.4 控制流

本文探讨了C++17中的if constexpr特性在模板函数中的应用,展示了如何在编译时条件判断类型,并通过例子演示了其使用。同时,提到了区间for迭代在现代C++中的实践,但代码示例存在错误,需要修复。

if constexpr

#include <iostream>

template<typename T>
auto print_type_info(const T& t) {
    if constexpr (std::is_integral<T>::value) {
        return t + 1;
    } else {
        return t + 0.001;
    }
}

// at compiling time
// int print_type_info(const int& t) {
//     return t + 1;
// }
// double print_type_info(const double& t) {
//     return t + 0.001;
// }

int main() {
    std::cout << print_type_info(5) << std::endl;
    std::cout << print_type_info(3.14) << std::endl;
}

g++ -std=c++17 2.10.if.constexpr.cpp -o ifcon 

在如下这篇博客中介绍了这一类问题出现的原因:

☞ 蓝桥ROS机器人之现代C++学习笔记2.2变量及其初始化 

此处给出一个简单方式:

en.cppreference.com/w/cpp/language/constexpr

在此网页直接可以编译并运行代码:

更进一步:

coliru.stacked-crooked.com

比蓝桥ROS还快捷,毕竟这是专业学习C++的^_^ 


区间 for 迭代

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec = {1, 2, 3, 4};
    if (auto itr = std::find(vec.begin(), vec.end(), 3); itr != vec.end()) *itr = 4;
    for (auto element : vec)
        std::cout << element << std::endl; // read only
    for (auto &element : vec) {
        element += 1;                      // writeable
    }
    for (auto element : vec)
        std::cout << element << std::endl; // read only
}

(⊙﹏⊙)

 


shiyanlou:2/ (master*) $ g++ -std=c++17 2.10.if.constexpr.cpp -o ifcon
2.10.if.constexpr.cpp: In function \u2018auto print_type_info(const T&)\u2019:
2.10.if.constexpr.cpp:14:8: error: expected \u2018(\u2019 before \u2018constexpr\u2019
     if constexpr (std::is_integral<T>::value) {
        ^
2.10.if.constexpr.cpp:16:7: error: \u2018else\u2019 without a previous \u2018if\u2019
     } else {
       ^
shiyanlou:2/ (master*) $ g++ -std=c++17 2.11.for.loop.cpp -o forloop [16:21:20]
2.11.for.loop.cpp: In function \u2018int main()\u2019:
2.11.for.loop.cpp:16:56: error: expected \u2018)\u2019 before \u2018;\u2019 token
     if (auto itr = std::find(vec.begin(), vec.end(), 3); itr != vec.end()) *itr
                                                        ^
2.11.for.loop.cpp:16:56: error: could not convert \u2018itr\u2019 from \u2018__gnu_cxx::__normal_iterator<int*, std::vector<int> >\u2019 to \u2018bool\u2019
2.11.for.loop.cpp:16:58: error: \u2018itr\u2019 was not declared in this scope
     if (auto itr = std::find(vec.begin(), vec.end(), 3); itr != vec.end()) *itr
                                                          ^
shiyanlou:2/ (master*) $                                             

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangrelay

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值