Skip to content

Instantly share code, notes, and snippets.

View picanumber's full-sized avatar

Nikos Athanasiou picanumber

View GitHub Profile
std::shared_ptr<Locking<X>> yy(std::make_shared<Locking<X>>(X{}));
(*yy.get())->f(msg);
// This is most likely unsafe, since we can only lock a single copy of the pointer
Locking<std::shared_ptr<X>> xx(std::make_shared<X>());
xx->get()->f(msg);
class X
{
int i = 0;
public:
int f(const char *msg) const
{
return i++;
}
};
template <class U> class CallProxy
{
U *_p;
std::recursive_mutex &_mtx;
mutable bool _own;
public:
CallProxy(U *pp, std::mutex &mtx) : _p(pp), _mtx(mtx), _own(true)
{
}
template <class T> class Locking
{
T _data;
mutable std::recursive_mutex _mtx;
/* Define call proxy here */
public:
template <class U> Locking(U &&data) : _data(std::forward<U>(data))
{
template <class T> class Locking
{
T _data;
mutable std::recursive_mutex _mtx;
template <class U> class CallProxy
{
U *_p;
std::recursive_mutex &_mtx;
mutable bool _own;
template <class T, class Tuple, std::size_t I = 0>
consteval std::size_t TypeIndex() {
if constexpr (I >= std::tuple_size<Tuple>::value) {
return 0;
} else if constexpr (std::is_same_v<T, std::tuple_element_t<I, Tuple>>) {
return I + 1;
} else {
return TypeIndex<T, Tuple, I + 1>();
}
}
@picanumber
picanumber / type_index_use.cpp
Last active July 8, 2020 21:23
Usage example of the type index predicate
type_index<int, std::tuple<char, int, float>>::value;
// Our type^^^ is found at index ^^^ 1 of our tuple
@picanumber
picanumber / flat_index_finder.cpp
Last active July 10, 2020 08:37
In place method to find the index of a type in a tuple
template <class T, std::size_t I, class Tuple> // 1
constexpr bool match_v = std::is_same_v<T, std::tuple_element_t<I, Tuple>>;
template <class T, class Tuple, // 2
class Idxs = std::make_index_sequence<std::tuple_size_v<Tuple>>>
struct type_index;
template <class T, template <class...> class Tuple, class... Args, // 3
std::size_t... Is>
struct type_index<T, Tuple<Args...>, std::index_sequence<Is...>>
@picanumber
picanumber / sorted_view_cpp17_custom_structured_bindings.cpp
Last active January 12, 2017 10:56
How to provide custom structured bindings for the sorted view class
namespace std
{
// 1. provide tuple_element<I, sorted_view<...>>::type
template <std::size_t I, class... Types>
struct tuple_element<I, utl::sorted_view<Types...>>
{
using sorted_view_t = utl::sorted_view<Types...>;
using type = typename sorted_view_t::template tuple_element_t<I>;
};
@picanumber
picanumber / sorted_view_cpp17_traversal_example.cpp
Created January 11, 2017 14:28
Traversing the sorted view with structured bindings
sv.multi_sort<6, 4, 5>([](auto&& a, auto&& b) { return a > b; });
auto [sName1, sName2, sSport, sGoldM, sSilverM, sBronzeM, sTotalM] = sv;
for (size_t i = 0; i < sv.size<6>(); i++)
{
std::cout << sTotalM[i] << " " << sGoldM[i] << " " << sSilverM[i] << " "
<< sName1[i] << " " << sName2[i] << std::endl;
}