首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从带有cv和引用限定符的std::function获取参数和返回类型?

如何从带有cv和引用限定符的std::function获取参数和返回类型?
EN

Stack Overflow用户
提问于 2015-09-09 19:08:55
回答 1查看 83关注 0票数 1

是否有一种从std::function获取参数和返回类型的好方法,以便我们也返回cv和引用限定符?这在一定程度上与前面的问题here有关。无论如何,使用答案中的代码,我们有以下示例:

代码语言:javascript
复制
#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&

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-09 19:19:04

const和引用是由typeid而不是function_traits剥离的。试着添加

代码语言:javascript
复制
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;

到您的foo,您将看到预期的值。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32487406

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档