Skip to content

Instantly share code, notes, and snippets.

@narodnik
Created January 23, 2019 10:53
Show Gist options
  • Save narodnik/8c80074231ecbaa3e58be822dd83510c to your computer and use it in GitHub Desktop.
Save narodnik/8c80074231ecbaa3e58be822dd83510c to your computer and use it in GitHub Desktop.
#include <iostream>
void foo()
{
std::cout << "foo" << std::endl;
}
void bar(int x)
{
std::cout << "bar" << std::endl;
}
// template traits class
template<class F>
struct function_traits;
// specialization using function pointer
template<class... Args>
struct function_traits<void (*)(Args...)>
{
static constexpr std::size_t number_parameters = sizeof...(Args);
};
template <typename Func>
void call(Func f)
{
if constexpr (function_traits<Func>::number_parameters == 0)
f();
else
f(0);
}
// Old way
template <typename Func,
typename std::enable_if_t<
function_traits<Func>::number_parameters == 0>* = nullptr>
void call_old(Func f)
{
f();
}
template <typename Func,
typename std::enable_if_t<
function_traits<Func>::number_parameters == 1>* = nullptr>
void call_old(Func f)
{
f(0);
}
int main()
{
call(foo);
call(bar);
call_old(foo);
call_old(bar);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment