Skip to content

Instantly share code, notes, and snippets.

@faithandbrave
Created March 23, 2021 06:37
Show Gist options
  • Save faithandbrave/47ed7b06ce9d0439488f6d032ea66df4 to your computer and use it in GitHub Desktop.
Save faithandbrave/47ed7b06ce9d0439488f6d032ea66df4 to your computer and use it in GitHub Desktop.
#include <type_traits>
#include <string>
#include <tuple>
template <class F>
struct function_traits : function_traits<decltype(&F::operator())> {};
template <class R, class... Args>
struct function_traits<R(Args...)> {
using args = std::tuple<Args...>;
using result_type = R;
};
template <class R, class T, class... Args>
struct function_traits<R(T::*)(Args...)> {
using args = std::tuple<Args...>;
using result_type = R;
};
template <class R, class T, class... Args>
struct function_traits<R(T::*)(Args...) const> {
using args = std::tuple<Args...>;
using result_type = R;
};
int f(int, double, std::string) { return 0; }
struct functor {
int operator()(const int&, const double&, std::string) { return 1; }
};
int main() {
auto g = [](std::string, double, int) { return 0; };
static_assert(std::is_same_v<
function_traits<decltype(f)>::args,
std::tuple<int, double, std::string>
>);
static_assert(std::is_same_v<
function_traits<decltype(g)>::args,
std::tuple<std::string, double, int>
>);
static_assert(std::is_same_v<
function_traits<functor>::args,
std::tuple<const int&, const double&, std::string>
>);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment