繁体   English   中英

检测功能参数类型

[英]Detecting function parameter type

我使用以下代码来检测给定函数的long参数。

因此,鉴于:

int f(int *) { return 0; }

我想提取int *

这是我的尝试:

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

但是,这不起作用,并且gcc 4.6给出了错误

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

因此,我有两个问题:

a)上面的代码有什么问题?

b)是否可以其他方式进行?

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

这对我有用:

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

有关拆包,请参见例如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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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