Info
-
Did you now that with concepts you can override a type?
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);
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>>);
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> {};
}
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
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>>);
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>>);
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>>);
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>>);