前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >蓝桥ROS机器人之现代C++学习笔记2.4 控制流

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

作者头像
zhangrelay
发布2022-04-29 19:33:59
2100
发布2022-04-29 19:33:59
举报

if constexpr

代码语言:javascript
复制
#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 迭代

代码语言:javascript
复制
#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
}

(⊙﹏⊙)

代码语言:javascript
复制
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*) $                                             
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-03-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档