I have written some template based codes to extract functions argument list in order to perform some strict type extraction and type checking. Here is part of code:
#include <type_traits>
#include <tuple>
#include <iostream>
template<typename>
struct function_traits {};
template <typename Return, typename... Args>
struct function_traits<Return (*)(Args...)>
{
template<std::size_t N>
using type = typename std::tuple_element<N, std::tuple<Args...>>::type;
static constexpr size_t callback_param_cnt = sizeof...(Args);
};
template<typename T, std::size_t N = function_traits<T>::callback_param_cnt>
struct callback_info {};
template<typename T>
struct callback_info<T, 1> {
constexpr static size_t val = function_traits<T>::callback_param_cnt;
};
template<typename T>
struct callback_info<T, 2> {
constexpr static size_t val = function_traits<T>::callback_param_cnt;
};
void foo(int) {
}
int main() {
function_traits<decltype(&foo)>::type<0> x;
std::cout << callback_info<decltype(&foo)>::val;
}
The code compiles without any problem. function_traits
extract function information including number and type of arguments. callback_info
just using function_traits
to extract some info for 1 and 2 argument functions. As you see, this code compiles without any problem and val
in callback_info
gets correct number of arguments(This is a test code to make sure that I can use function_traits
inside callback_info
). But here is my problem: event though my function_traits::type
works in the main
, I want to use it in callback_info
to save argument types. Something like this:
template<typename T, std::size_t N = function_traits<T>::callback_param_cnt>
struct callback_info {};
template<typename T>
struct callback_info<T, 1> {
using Type1 = typename function_traits<T>::type<0>;
constexpr static size_t val = function_traits<T>::callback_param_cnt;
};
template<typename T>
struct callback_info<T, 2> {
using Type1 = typename function_traits<T>::type<0>;
using Type2 = typename function_traits<T>::type<1>;
constexpr static size_t val = function_traits<T>::callback_param_cnt;
};
But this code does not compile. It seems because template deduction fails, it cannot find type
here. Why this happens? How I can solve this problem? In addition, how I can change function_traits
to detect reference arguments too? because it currently detect int&
argument as int
right now.