Skip to content

Instantly share code, notes, and snippets.

View meshell's full-sized avatar

Michel Estermann meshell

View GitHub Profile
#include <string>
#include <vector>
struct Type
{
Type(std::string, float) {};
Type(Type const &) = delete;
Type(Type &&) = default;
};
#include <type_traits>
template <class T>
void swap(T& a, T& b) {
static_assert(std::is_copy_constructible<T>::value,
"Swap requires copying");
static_assert(std::is_nothrow_move_constructible<T>::value
&& std::is_nothrow_move_assignable<T>::value,
"Swap may throw");
auto c = b;
#include <iostream>
#include <chrono>
// used as conversion
constexpr long double operator"" _m ( long double m ) {
return m;
}
constexpr long double operator"" _km ( long double km ) {
return km * 1000.0_m;
@meshell
meshell / CppUG_constexpr.cpp
Created February 22, 2016 21:57
constexpr example from "Effective Modern C++" by Scott Meyers, Item 15
#include <array>
#include <iostream>
#if __cplusplus > 201103L
constexpr int pow(int base, int exp) noexcept
{
auto result = 1;
for (int i = 0; i < exp; ++ i) {
result *= base;
}
@meshell
meshell / CppUG_STL.h
Last active February 22, 2016 21:56
Examples using Standard library Algorithms
#include <algorithm>
#if __cplusplus > 201103L
// for C++14 use
using std::cbegin;
using std::cend;
#else
// C++11 does not implement non-member version of cbegin and cend.
// Therefor for a C++11 only compiler use
template<class C>
// Classic C++ declaration order // Modern C++ style
const char* s = "Hello"; auto s = "Hello";
widget w = get_widget(); auto w = get_widget();
employee e{ empid }; auto e = employee{ empid };
widget w{ 12, 34 }; auto w = widget{ 12, 34 };
unique_ptr<widget> w auto w = make_unique<widget>();
= make_unique<widget>();
int x = 42; auto x = 42;
float x = 42.; auto x = 42.f;
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {0, 1, 2, 3, 4, 5};
for(const auto& i : v) {
std::cout << i << ' ';
}
std::cout << '\n';
#include <vector>
// Until C++11
std::vector<int> v;
//v is swapped with its temporary copy, which is capacity optimal
std::vector<int>(v.begin(), v.end()).swap(v);
// Since C++11
std::vector<int> v2;
v2.shrink_to_fit();
struct base {
virtual std::string name() { return "default"; }
virtual void foo() final { }
};
struct derived final: public base {
std::string name() override { return "derived!" }
// compile error: overriding final function 'virtual void base::foo()'
void foo() override { }
};
struct base {
virtual std::string name() { return "default"; }
};
struct derived : public base {
// compile error: 'std::string derived::mame()' marked 'override', but does not override
std::string mame() override { return "derived!" }
};