简体   繁体   中英

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?

#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");
}

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 eg abi::__cxa_demangle .

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM