Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
#include <iostream> #include <map> #include <string> #include <type_traits> #include <concepts> // C++20 // C++20 Concept: requires arithmetic type template<typename T> concept Numeric = std::is_arithmetic_v<T>; // Constrained function template template<Numeric T> T square(T value) { return value * value; } // if constexpr: compile-time branching inside template template<typename T> std::string describe(T val) { if constexpr (std::is_integral_v<T>) return "integer: " + std::to_string(val); else if constexpr (std::is_floating_point_v<T>) return "float: " + std::to_string(val); else return "other"; } int main() { // Structured bindings with map iteration (C++17) std::map<std::string, int> inventory = { {"apples", 10}, {"bananas", 5}, {"cherries", 25} }; for (const auto& [item, qty] : inventory) std::cout << item << ": " << qty << " "; // Structured binding with pair auto [q, r] = std::pair{17 / 5, 17 % 5}; std::cout << "17 / 5 = " << q << " remainder " << r << " "; // if constexpr in template std::cout << describe(42) << " "; std::cout << describe(3.14) << " "; // Concepts: square only works for Numeric types std::cout << "square(7) = " << square(7) << " "; std::cout << "square(2.5) = " << square(2.5) << " "; // square("hi") would be a clear concept violation error return 0; }
Result
Open