2017-07-13 7 views
0

私はRAIIを実行するクラスのサンプルプログラムを作成しようとしており、このポインタを使ってスレッドを呼び出します。スレッド関数の引数のデータ型は先行宣言として宣言されています。 サンプルプログラムの外観を持っていてください -スレッド関数引数の前方宣言が機能していません

#include <iostream> 
#include <thread> 

using namespace std; 

class test; // **forward declaration** 

void thfunc (test *p) { 
    cout << p->value << endl; 
    return; 
} 

class test { 
    public: 
     int value; 
     thread t1; 
     test() { 
      value = 100; 
      t1 = thread(thfunc, this); 
     } 
     ~test() { 
      t1.join(); 
     } 
}; 

int main() { 
    test * p = new test; 
    delete p; 
    return 0; 
} 

これはコンパイルエラー与えている -

fwd.cpp: In function 'void thfunc(test*)': 
fwd.cpp:9:11: error: invalid use of incomplete type 'class test' 
fwd.cpp:6:7: error: forward declaration of 'class test' 

これを修正するには、私はクラスの静的メンバ関数としてのスレッド関数を作った -

class test { 
    public: 
     int value; 
     thread t1; 
     test() { 
      value = 100; 
      t1 = thread(thfunc, this); 
     } 
     ~test() { 
      t1.join(); 
      cout << "Dtor" << endl; 
     } 
     **static** void thfunc (test *p) { 
      cout << p->value << endl; 
      return; 
     } 

}; 

これは正しい修正ですか?スレッド関数を別のライブラリとして作成したいのですが、今はそれらをクラスの一部として作成する必要があります。提案してください。どんな種類のヘルプ/ポインタ/提案も感謝します。

+1

はどのようにコンパイラが 'p型> [値]が何であるかを知っていることになっていますか?それは 'クラステスト;を見る機会があっただけです。 – StoryTeller

+0

ここでは使用例が見当たりません。スレッド関数でクラスのインスタンスを使用する場合は、どのように見えるかを知る必要があります。そのため、他のモジュールのスレッド関数はクラスを記述するヘッダーを含める必要があります。インスタンスを使用する予定がない場合は、最初にスレッド関数に渡すのはなぜですか?だから私は、静的メンバーははるかに理にかなっていると思う.... – BitTickler

+0

これはスレッドとは関係ありません。 – juanchopanza

答えて

0

thfuncを静的メンバーにすることは、それがうまくいくという意味では正しいです。何らかの理由でそれらを分離しておきたいのであれば(そして時には非常に良い理由がある)、それでもあなたはそれを行うことができます。

にのみstd::threadへの引数として渡される前に宣言することができ、関数の:

#include <iostream> 
#include <thread> 

using namespace std; 

void thfunc (class test *p); 

class test { 
    public: 
     int value; 
     thread t1; 
     test() { 
      value = 100; 
      t1 = thread(thfunc, this); 
     } 
     ~test() { 
      t1.join(); 
     } 
}; 

void thfunc (test *p) { 
    cout << p->value << endl; 
    return; 
} 

int main() { 
    test * p = new test; 
    delete p; 
    return 0; 
} 
+0

ありがとう、それは私が探していた正確なトリックthats。あなたは私の日を救った:) –

関連する問題