Skip to content

Instantly share code, notes, and snippets.

@Dich0tomy
Created July 8, 2022 21:23
Show Gist options
  • Save Dich0tomy/cd194e39ade91912bec52dcdf692f4d5 to your computer and use it in GitHub Desktop.
Save Dich0tomy/cd194e39ade91912bec52dcdf692f4d5 to your computer and use it in GitHub Desktop.
A simple C++11 detection idiom presented.
#include <type_traits>
#include <iostream>
#include <utility>
namespace mystd {
namespace detail {
template <typename...>
using void_t = void;
template <typename T, typename Void = void>
struct has_swap : std::false_type {};
template <typename T>
struct has_swap<T, void_t<decltype(std::declval<T>().swap(std::declval<T&>()))>> : std::true_type {};
template <typename T>
static inline auto constexpr has_swap_v = has_swap<T>::value;
}
template <typename T>
auto swap(T& a, T& b) -> typename std::enable_if<detail::has_swap_v<T>>::type {
std::cout << "Member swap.\n";
}
template <typename T>
auto swap(T& a, T& b) -> typename std::enable_if<not detail::has_swap_v<T>>::type {
std::cout << "Free swap.\n";
}
}
auto main() -> int {
struct HasMemberSwap {
void swap(HasMemberSwap&) {}
};
struct DoesntHaveMemberSwap {};
{
HasMemberSwap a, b;
mystd::swap(a, b);
}
{
DoesntHaveMemberSwap a, b;
mystd::swap(a, b);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment