Chubsdad
Chubsdad

Reputation: 25497

Detecting function parameter type

I went about with the following code to detect the long argument to a given function.

So, given:

int f(int *) { return 0; }

I want to extract int *.

Here is my attempt:

template<class T, class U> struct SingleArg {
    typedef U MyArg;
};

template<class T, class U> SingleArg<T, U> fT(T (*p)(U));

int main() {
    std::result_of<decltype(fT(f))>::type::MyArg t;
}

This however does not work and gcc 4.6 gives error

> error: std::result_of<SingleArg<int, int*> >::type has not been
> declared

So, I have two questions:

a) What's wrong with the above code?

b) Is it possible to do this in any other way/ways?

Upvotes: 2

Views: 859

Answers (3)

Boris L.
Boris L.

Reputation: 91

#include <type_traits>

template <typename Function>
struct arg_type;

template <class Ret, class Arg>
struct arg_type<Ret(Arg)> {
  typedef Arg type;
};


int f(int *) {
  return 0;
};

int main(int, char**) {
  static_assert(std::is_same<int*, arg_type<decltype(f)>::type>::value, "different types");
}

Upvotes: 5

user396672
user396672

Reputation: 3166

int f(int *) { return 0; }

template<class T, class U> struct SingleArg {
    typedef U MyArg;
};


template<typename T> 
struct the_same_type
{
 typedef T type;   
};

template<class T, class U> SingleArg<T, U> fT(T (*p)(U));

int main() {

    int k;
    the_same_type<decltype(fT(f))>::type::MyArg t= &k;
    return 0;
}

Upvotes: 0

Anders Johansson
Anders Johansson

Reputation: 4006

This works for me:

// if you want the type
typedef decltype(fT(f))::MyArg theType;

// if you want the name (may need demangling depending on your compiler)
std::cout << typeid(decltype(fT(f))::MyArg).name() << std::endl;

For demangling, see e.g. abi::__cxa_demangle.

Upvotes: 0

Related Questions