模板,函数指针和C ++ 0x [英] Templates, Function Pointers and C++0x

查看:136
本文介绍了模板,函数指针和C ++ 0x的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我个人的实验之一,了解一些C ++ 0x功能:我试图传递一个函数指针到模板函数执行。最终,执行应该发生在不同的线程中。但是对于所有不同类型的函数,我不能得到模板工作。

One of my personal experiments to understand some of the C++0x features: I'm trying to pass a function pointer to a template function to execute. Eventually the execution is supposed to happen in a different thread. But with all the different types of functions, I can't get the templates to work.

#include <functional>

int foo(void) {return 2;}

class bar {
public:
    int operator() (void) {return 4;};
    int something(int a) {return a;};
};

template <class C>
int func(C&& c)
{
    //typedef typename std::result_of< C() >::type result_type;
    typedef typename std::conditional< 
        std::is_pointer< C >::value,
        std::result_of< C() >::type,
        std::conditional<
            std::is_object< C >::value,
            std::result_of< typename C::operator() >::type,
            void>
        >::type result_type;
    result_type result = c();
    return result;
}

int main(int argc, char* argv[])
{
    // call with a function pointer
    func(foo);

    // call with a member function
    bar b;
    func(b);

    // call with a bind expression
    func(std::bind(&bar::something, b, 42));

    // call with a lambda expression
    func( [](void)->int {return 12;} );

    return 0;
}

result_of模板似乎不能找到运算符)在类别栏和clunky条件我创建不编译。有任何想法吗?如果使用 decltype

The result_of template alone doesn't seem to be able to find the operator() in class bar and the clunky conditional I created doesn't compile. Any ideas? Will I have additional problems with const functions?

推荐答案

>?

template <class C>
auto func(C&& c) -> decltype(c()) {
    auto result = c();
    return result;
}

这篇关于模板,函数指针和C ++ 0x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆