如何使用cv和引用限定符从std :: function中获取参数并返回类型?

wye*_*r33 1 c++ c++11 c++14

是否有一个很好的方法来获取参数并返回类型,std::function以便我们还返回cv和引用限定符?这部分涉及到前一个问题在这里.无论如何,使用答案中的代码,我们有以下示例:

#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);
}
Run Code Online (Sandbox Code Playgroud)

现在,使用c ++ filt,我们看到fis std::function<double (double)>的类型和gis 的类型std::function<double (double const&)>.但是,结构function_traits报告参数类型是相同的,它们不是.基本上,const&被剥离了参数类型g.有没有办法解决这个问题,以便const&保留?

asc*_*ler 5

const和参考被剥离typeid,而不是由function_traits.尝试添加

std::cout << std::boolalpha << std::is_same<double,
    typename function_traits<T>::template arg<0>::type>::value  << std::endl;
std::cout << std::boolalpha << std::is_same<const double&,
    typename function_traits<T>::template arg<0>::type>::value << std::endl;
Run Code Online (Sandbox Code Playgroud)

到你的foo,你会看到预期的价值.