Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

#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 e.g. abi::__cxa_demangle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top