Skip to content

Latest commit

 

History

History
115 lines (84 loc) · 2.72 KB

302.md

File metadata and controls

115 lines (84 loc) · 2.72 KB
Info

Example

template<auto N> struct foo  {
  static constexpr auto value = N;
};
static_assert(42 == foo<42>::value);

template<auto N>
  requires true // override -> more specialized
struct foo<N> {
  static constexpr auto value = 0;
};
static_assert(42 == foo<42>::value); // memoized
static_assert(0 == foo<43>::value);

https://godbolt.org/z/hPcsKG4an

Puzzle

  • Can you override std::shared_ptr to avoid thred-safe guards?
#include <memory>

// TODO override shared_ptr with std::__shared_ptr<int, __gnu_cxx::_S_single> which is is not thread-safe
// NOTE overriding STL is UB
// Alternative - boost::local_shared_ptr

#include <type_traits>
static_assert(std::is_base_of_v<std::__shared_ptr<int, __gnu_cxx::_S_single>, std::shared_ptr<int>>);

https://godbolt.org/z/7axP5or3q

Solutions

namespace std {
    template<class T> requires ::std::is_same_v<T, int>
    class shared_ptr<T> : public __shared_ptr<int, __gnu_cxx::_S_single> {};
}

https://godbolt.org/z/Mhj1M7Yec

namespace std {
template <class T>
    requires std::is_integral_v<T>
class shared_ptr<T> : public __shared_ptr<int, __gnu_cxx::_S_single> {};
}  // namespace std

https://godbolt.org/z/sa9a937of

namespace boost{
    template<typename N> requires std::is_same_v<int,N>
    struct shared_ptr<N> : std::__shared_ptr<N, __gnu_cxx::_S_single> {
    };
}

static_assert(std::is_base_of_v<std::__shared_ptr<int, __gnu_cxx::_S_single>, boost::shared_ptr<int>>);

https://godbolt.org/z/acWKbG4fG

namespace std{
    template<typename N> requires is_same_v<int,N>
    struct shared_ptr<N> : std::__shared_ptr<N, __gnu_cxx::_S_single> {
    };
}

static_assert(std::is_base_of_v<std::__shared_ptr<int, __gnu_cxx::_S_single>, std::shared_ptr<int>>);

https://godbolt.org/z/z7YznT45n

template <class T>
concept integral = std::is_integral_v<T>;

namespace std{
    template<integral T>
    class shared_ptr<T> : public std::__shared_ptr<T, __gnu_cxx::_S_single>{
    };
}

#include <type_traits>
static_assert(std::is_base_of_v<std::__shared_ptr<int, __gnu_cxx::_S_single>, std::shared_ptr<int>>);

https://godbolt.org/z/PP6KEczMb

template<typename T>
requires true
class std::shared_ptr<T> : std::__shared_ptr<T, __gnu_cxx::_S_single> {
};

#include <type_traits>
static_assert(std::is_base_of_v<std::__shared_ptr<int, __gnu_cxx::_S_single>, std::shared_ptr<int>>);

https://godbolt.org/z/rrr8GP3qe