I have a function traits struct that provides the types of a function's arguments using std::tuple_element
:
#include <iostream>
#include <tuple>
#include <typeinfo>
template <typename T>
struct function_traits;
template <typename T_Ret, typename ...T_Args>
struct function_traits<T_Ret(T_Args...)> {
// Number of arguments.
enum { arity = sizeof...(T_Args) };
// Argument types.
template <size_t i>
struct args {
using type
= typename std::tuple_element<i, std::tuple<T_Args...>>::type;
};
};
int main() {
using Arg0 = function_traits<int(float)>::args<0>::type;
//using Arg1 = function_traits<int(float)>::args<1>::type; // Error, should be void.
std::cout << typeid(Arg0).name() << std::endl;
//std::cout << typeid(Arg1).name() << std::endl;
}
Working example: Ideone
If the index i
is out of range (>= arity
), this gives a compile-time error. Instead, I would like args<i>::type
to be void
for any i
out of range.
While I can specialize args
for specific i
, such as i == arity
, how could I go about specializing args
for all i >= arity
?
With std::conditional
and extra indirection:
struct void_type { using type = void; };
template <typename T_Ret, typename ...T_Args>
struct function_traits<T_Ret(T_Args...)> {
// Number of arguments.
enum { arity = sizeof...(T_Args) };
// Argument types.
template <size_t i>
struct args {
using type
= typename std::conditional<(i < sizeof...(T_Args)),
std::tuple_element<i, std::tuple<T_Args...>>,
void_type>::type::type;
};
};
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With