Created
April 21, 2014 21:44
-
-
Save apples/11157610 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <tuple> | |
#include <utility> | |
// Smart pointers | |
struct SampleStruct | |
{ | |
int x = 0; | |
SampleStruct(int a, int b, int c) | |
: x(a*b+c) | |
{} | |
}; | |
void sample_smart_ptr() | |
{ | |
auto ptr = std::make_unique<SampleStruct>(7, 42, 69); | |
ptr->x = 13; | |
} | |
// ptr automatically deleted. | |
// Factory (CRTP) | |
class Base | |
{ | |
public: | |
virtual ~Base() = 0; | |
virtual std::unique_ptr<Base> clone() const = 0; | |
}; | |
inline Base::~Base() | |
{} | |
template <typename Child> | |
class Factory | |
: public Base | |
{ | |
virtual std::unique_ptr<Base> clone() const override | |
{ | |
auto const& self = static_cast<Child const&>(*this); | |
return std::make_unique<Child>(self); | |
} | |
}; | |
class SampleChild | |
: public Factory<SampleChild> | |
{}; | |
// | |
void sample_factory() | |
{ | |
std::unique_ptr<Base> ptr1 = std::make_unique<SampleChild>(); | |
std::unique_ptr<Base> ptr2 = ptr1->clone(); | |
} | |
// Static type ID | |
int make_id() | |
{ | |
static int id = 0; | |
return ++id; | |
} | |
template <typename T> | |
int getID() | |
{ | |
static int id = make_id(); | |
return id; | |
} | |
// | |
void sample_static_id() | |
{ | |
int id_int = getID<int>(); // == 1 | |
int id_double = getID<double>(); // == 2 | |
int id_bool = getID<bool>(); // == 3 | |
} | |
// Range-based for loops | |
// C++03 | |
int sample_ranged_03(vector<int> const& nums) | |
{ | |
int sum = 0; | |
{ | |
vector<int>::const_iterator _iter = nums.begin(); | |
vector<int>::const_iterator _end = nums.end(); | |
for (; _iter != _end; ++_iter) | |
{ | |
int const& i = *_iter; | |
sum += i; | |
} | |
} | |
return sum; | |
} | |
// C++11 | |
int sample_ranged_11(vector<int> const& nums) | |
{ | |
int sum = 0; | |
for (auto&& i : nums) | |
sum += i; | |
return sum; | |
} | |
// Stopwatch | |
struct Stopwatch | |
{ | |
using Clock = std::chrono::high_precision_clock; | |
using Unit = std::chrono::nanosecond; | |
Clock::time_point st; | |
void start() | |
{ | |
st = Clock::now(); | |
} | |
Unit stop() const | |
{ | |
auto stp = Clock::now(); | |
return std::chrono::duration_cast<Unit>(stp-st); | |
} | |
}; | |
// | |
void sample_stopwatch() | |
{ | |
Stopwatch sw; | |
Stopwatch::Unit dur; | |
sw.start(); | |
expensive_operation(); | |
dur = sw.stop(); | |
std::cout << "Benchmark: " << dur << "ns" << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment