Skip to content

Instantly share code, notes, and snippets.

View odeblic's full-sized avatar

Olivier de BLIC odeblic

View GitHub Profile
@odeblic
odeblic / variadic_inheritance.cpp
Last active July 27, 2017 11:23
Inherit several bases by using variadic templates
#include <iostream>
#include <type_traits>
#include <typeinfo>
template <typename BASE, typename ... BASES>
struct MultiDerived : BASE, MultiDerived<BASES> ...
{
void EveryAction()
{
BASE::Action();
@odeblic
odeblic / metaprogramming.cpp
Last active July 27, 2017 11:25
Metaprogramming with compile-time computed fibonacci and factorial functions
#include <iostream>
template <unsigned int N>
struct factorial
{
enum { value = N * factorial<N - 1>::value };
};
template <>
struct factorial<0>
@odeblic
odeblic / except.cpp
Last active July 27, 2017 11:26
Exception handling, enabled or not
#include <iostream>
#include <exception>
#include <cstdlib>
void f() noexcept(false)
{
std::cout << "f()" << std::endl;
throw('F');
}
@odeblic
odeblic / call_once.cpp
Last active July 27, 2017 11:27
Simple example for std::call_once
#include <iostream>
#include <mutex>
#include <functional>
struct Object
{
Object(int n) : n(n) {}
void init() { std::call_once(initialized, [this] { std::cout << "init with n=" << n << std::endl; }); }
@odeblic
odeblic / move.cpp
Last active July 27, 2017 11:28
Several use cases around move semantic
#include <iostream>
#include <mutex>
struct Object
{
Object(int id) : id(id)
{
std::cout << '[' << id << "] constructor" << std::endl;
}
@odeblic
odeblic / callable.cpp
Last active July 27, 2017 11:29
Construction of callable objects
#include <iostream>
#include <thread>
#include <list>
struct Object
{
void method(int n) {}
void operator()(int n) {}
};
@odeblic
odeblic / async.cpp
Last active July 27, 2017 11:29
Asynchronous features (async, promises, futures)
#include <iostream>
#include <future>
#include <thread>
std::mutex mu;
template <typename T>
void print(std::string message, T data)
{
std::lock_guard<std::mutex> lg(mu);
@odeblic
odeblic / locks.cpp
Last active July 27, 2017 11:30
Deadlock avoidance with std::lock
#include <iostream>
#include <mutex>
struct Lock
{
Lock(int id) : id(id) {}
void lock() { std::cout << "lock() from " << id << std::endl; }
bool try_lock() { std::cout << "try_lock() from " << id << std::endl; return true; }
void unlock() { std::cout << "unlock() from " << id << std::endl; }
int id;
@odeblic
odeblic / lambdas.cpp
Last active July 27, 2017 11:30
How capture work with lambda functions
#include <iostream>
int main(void)
{
int a = 1001;
long double b = 3.1415926;
char c = 'A';
std::string d = "I like C";
std::cout << "a: " << a << std::endl;
@odeblic
odeblic / new.cpp
Last active July 27, 2017 11:31
Different versions of new operator
#include <iostream>
struct Object
{
Object(int n = 0) : n(n)
{ std::cout << '[' << n << ']' << " Object::Object()" << std::endl; }
~Object()
{ std::cout << '[' << n << ']' << " Object::~Object()" << std::endl; }