【发布时间】:2015-09-09 19:08:55
【问题描述】:
有没有一种从std::function 获取参数和返回类型的好方法,这样我们也可以返回 cv 和引用限定符?这部分与之前的问题here 有关。无论如何,使用答案中的代码,我们有以下示例:
#include <functional>
#include <iostream>
template<typename T>
struct function_traits;
template<typename R, typename ...Args>
struct function_traits<std::function<R(Args...)>> {
static const size_t nargs = sizeof...(Args);
typedef R result_type;
template <size_t i>
struct arg {
typedef typename std::tuple_element<i, std::tuple<Args...>>::type
type;
};
};
template <typename T>
void foo(T const & f) {
typedef function_traits <T> stuff;
std::cout <<
typeid(typename function_traits <T>::result_type).name()
<< std::endl;
std::cout <<
typeid(typename function_traits <T>::template arg<0>::type).name()
<< std::endl;
std::cout << typeid(T).name() << std::endl;
}
int main() {
std::cout << "Function: f" << std::endl;
auto f = [](double x) { return x+1.;};
foo <std::function<double(double)>> (f);
std::cout << std::endl << "Function: g" << std::endl;
auto g = [](double const & x) { return x+1.;};
foo <std::function<double(double const &)>> (g);
}
现在,使用 c++filt,我们看到 f 的类型是 std::function<double (double)>,g 的类型是 std::function<double (double const&)>。但是,结构function_traits 报告参数类型是相同的,但事实并非如此。基本上,const& 被剥离了g 的参数类型。有没有办法解决这个问题,以便保留const&?
【问题讨论】: