奇怪的重复模板模式与ptrhead

时间:2014-08-27 02:05:20

标签: c++ templates crtp

所以我试图弄清楚你是否可以使用奇怪的重复模板模式来解决pthread使用类方法的限制,甚至通过做类似的事情来创建类。

template <class T>
class thread_helper
{
  static void* create(void *input)
  {
     T * output=new T;
     return static_cast<void*>(output);
  }

  static void* using(void *input)
  {
    T::use(input);
  }
};

class user : public thread_helper<user>
{
  void method(int x)
  {
    //does something
  }
  static void use(void* input)
  {
    this->method(static_cast<int>(input));
  }
};

然后您可以使用pthread使用

调用类创建
pthread_create(thread_variable, NULL, thread_helper::create<some_class>, void);

和另一个电话

pthread_create(thread_variable, NULL, user::using(), void);

注意:上面的代码中有很多错误。请不要为我们分开。我真的只是想描绘一下我想要做的事情。我也在试图弄清楚是否有更好的方法来进行这项操作。

另外第二个pthread_create方法真的有必要我也不能只使用构造函数吗?

1 个答案:

答案 0 :(得分:0)

我将发布一个有效的测试代码。它涉及大量的锅炉板代码。看起来很丑,但很有效。注意:我可能会在以后更改thread_helper的create方法,因此它不能用于线程。

#include <iostream>
#include "pthread.h"

using namespace std;

template <class I>
struct helper
{
    void *(I::*method)(void *); //enables you to call and get information from any non static class method
    I *ptr; //this is the class pointer used to call the member pointer
    void *info; //this is what you pass into the member pointer
};

template <class T>
class thread_helper
{
public:
    static void *create(void *in)
    {
        T * output=new T;
        return static_cast<void*>(output);
    }

    static void *method(void *in)
    {
        helper<T> *utilize = static_cast<helper<T> *>(in);
        return (utilize->ptr->*utilize->method)(utilize->info);
    }
};

class test: public thread_helper<test>
{
public:
    void *test_method(void *in)
    {
        int *val = (int *)in;//note: not static_casting since this is not a class
        *val *= 4;
        return val; //auto casts to void *
    }
};

int main()
{
    //initialize test
    test * second = static_cast<test*>(test::create(NULL));

    //initialize helper
    helper<test> first;
    first.ptr = second;
    first.method = &test::test_method;
    int val = 4;
    first.info = &val;//

    //setup threads
    pthread_t thread;
    void *ans;

    //call test_method and retrieve answer
    pthread_create(&thread, NULL, test::method, static_cast<void *>(&first));
    pthread_join(thread, &ans);

    cout << "the answer is "<< *(int *)ans <<endl;
    return 0;
}

正如所指出的,如果你使用pthreads,这个解决方案是有效的。并且是编写函数或静态方法来调用类的方法的通用替代。

如果您使用的是boost或c ++ 11线程,则不需要使用此方法,并且可能不应该使用它,因为它需要大量的样板代码(指针转换)。