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*) $