加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 模板参数作为仿函数模板

发布时间:2020-12-16 09:38:16 所属栏目:百科 来源:网络整理
导读:我正在尝试创建一个从适配器执行仿函数的线程类.代码显示了我的尝试. #include iostreamstruct null_t { };typedef void (*thread_func_t)();typedef void (*thread_func_2_t)(int);template typename F,typename P = null_tclass adapter{public: adapter(F
我正在尝试创建一个从适配器执行仿函数的线程类.代码显示了我的尝试.

#include <iostream>

struct null_t { };

typedef void (*thread_func_t)();
typedef void (*thread_func_2_t)(int);

template <typename F,typename P = null_t>
class adapter
{
public:
    adapter(F f,P p = null_t()) : _f(f),_p(p) {}

    void operator ()() 
    {
        _f(_p);
    }
private:
    F _f;
    P _p;
};

template <typename T>
class thread
{
public:
    explicit thread(T f) : _f(f) { }

    void run()
    {
        _f();
    }
private:
    T _f;
};

void show_hello()
{
    std::cout << "hello" << std::endl;
}

void show_num(int x)
{
    std::cout << "show_num: " << x << std::endl;
}

int main()
{
    thread<adapter<thread_func_t> > t_a(adapter<thread_func_t>(&show_hello));

    t_a.run();

    int i = 666;
    thread<adapter<thread_func_2_t,int> > t_b(adapter<thread_func_2_t,int>(&show_num,i));
    t_b.run();
}

编译错误:

$/usr/bin/g++-4.4 func.cpp -o func
func.cpp: In function ‘int main()’:
func.cpp:51: error: request for member ‘run’ in ‘t_a’,which is of non-class type ‘thread<adapter<void (*)(),null_t> >(adapter<void (*)(),null_t>&)’

1)适配器不准备调用没有参数的函数. (我不知道该怎么做).

2)我已经尝试过线程接收模板模板参数但没有成功.

我试图做的几乎与下面的示例相同(此适配器不适用于没有参数的函数):

typedef void (*WorkerFunPtr)(const std::string&);

template<typename FunT,typename ParamT>
struct Adapter {
    Adapter(FunT f,ParamT& p) : f_(f),p_(&p) {}

    void operator( )( ) {
        f_(*p_);
    }
    private:
    FunT f_;
    ParamT* p_;
};

void worker(const std::string& s) { std::cout << s << 'n'; }

int main( ) {
    std::string s1 = "This is the first thread!";
    boost::thread thr1(Adapter<WorkerFunPtr,std::string>(worker,s1));

    thr2.join( );
}

解决方法

这是 Most Vexing Parse问题.您需要在构造函数参数周围添加另一对括号,否则该行将被视为函数声明.

thread<adapter<thread_func_t> > t_a((adapter<thread_func_t>(&show_hello)));

另外,考虑使用boost :: thread,因为它会将您的代码转换为三行代码.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读