Skip to content

Instantly share code, notes, and snippets.

@hatsusato
hatsusato / union1.c
Created December 22, 2013 18:07
snipet of union in C for KMC Advent Calendar 2013
struct Si {
char tag;
int i;
};
struct Sp {
char tag;
int* p;
};
union U {
int i;
@hatsusato
hatsusato / union2.cpp
Last active January 1, 2016 03:29
snipet of union in C++03 for KMC Advent Calendar 2013
template <typename T> // テンプレート共用体だって作れる
union U {
private:
struct {
bool is_allocated;
T i;
} si;
struct {
bool is_allocated;
T* p;
@hatsusato
hatsusato / union3.cpp
Last active January 1, 2016 03:29
snipet of union in C++03 for KMC Advent Calendar 2013
template <typename T>
class BetterU {
bool is_allocated;
union { // 余分な構造体が必要ない
T i;
T* p;
};
void Clean() {
if (IsAllocated()) { delete p; }
}
@hatsusato
hatsusato / union4.cpp
Last active January 1, 2016 03:29
snipet of union in C++11 for KMC Advent Calendar 2013
class U {
enum class Tag { String, Vector } tag;
union {
std::string s;
std::vector<int> v;
};
void Clean() {
switch (tag) {
case Tag::String:
s.~basic_string();
@hatsusato
hatsusato / union5.cpp
Last active January 1, 2016 03:59
snipet of union in C++11 for KMC Advent Calendar 2013
union Safe {
Safe(const char* src) : s{src} {}
~Safe() { s.~basic_string(); }
unsigned long long ull{0ULL}; // クラス内初期化は1つまで
std::string s;
};
union Danger {
Danger(const char* src) : s{src} {}
~Danger() { s.~basic_string(); }
std::string s;
@hatsusato
hatsusato / make_unique.hpp
Last active January 26, 2016 14:31
make_unique
#include <memory>
#include <type_traits>
template <class T, class... Args>
typename std::enable_if<std::is_constructible<T, Args...>::value,
std::unique_ptr<T> >::type
make_unique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template <class T, class... Args>
// template <class T, T... Ints> class integer_sequence; // in <utility> since C++14
template <size_t... N>
struct IntegerSeq {
using type = IntegerSeq;
static constexpr size_t size() { return sizeof...(N); }
};
template <typename S, typename T>
struct ConcatSeq_;
@hatsusato
hatsusato / apply.hpp
Created June 21, 2015 17:08
unpack tuple and apply them to a function
#include <tuple>
#include <type_traits>
#include "integer_sequence.hpp"
template <typename T>
using resultof = typename std::result_of<T>::type;
template <typename F, typename... Args, size_t... I>
auto apply_(F&& f, std::tuple<Args...>&& args, IntegerSeq<I...>)
-> resultof<F(Args...)> {
#include <type_traits>
// Usage: template <enabler_type<condition> = nullptr>
template <bool B>
using enabler_type = typename std::enable_if<B, std::nullptr_t>::type;
@hatsusato
hatsusato / prime_sequence.cpp
Last active February 8, 2016 07:42
generate compile-time prime table
#include <array>
#include <iostream>
#include <type_traits>
#define ENABLER(cond) \
typename std::enable_if<(cond), std::nullptr_t>::type = nullptr
template <typename T, T... N>
struct IntegerSequence;