2017-07-20 3 views
0

私は、スレッド数に対する符号なしのintパラメータを持つテンプレート・クラスを持っています。私はスレッドのための静的な配列を作成するためにそれを使用したいと思います。私は、デフォルト値としてstd::thread::hardware_concurrency()使用することはできませんどちらもテンプレート・パラメータとしてthread :: hardware_concurrency()

template <typename T, size_t num_threads = std::thread::hardware_concurrency()> 
    class Some_class{ 
     T values[num_threads]; 
     ... 
} 

もパラメータとして私のクラスにそれを与えます。

template <typename T, size_t num_threads> 
     class Some_class{ 
      T values[num_threads]; 
      ... 
    } 

Some_class<int,std::thread::hardware_concurrency()> instance; 

問題がstd::thread::hardware_concurrency()の戻り値はconstのないことです。

コンパイラは言う:

error: call to non-constexpr function ‘static unsigned int std::thread::hardware_concurrency()’ 

note: in template argument for type ‘long unsigned int’ 

は私のテンプレートで使用可能なスレッド数を取得するには、別の静的な方法はありますか?

+0

*定数式*はC++テンプレートでのみ使用できます。残念ながら 'std :: thread :: hardware_concurrency()'は*定数式ではなく、実行時にしか評価できません – WhiZTiM

+0

どのOSを使用していますか? – WhiZTiM

答えて

0

システム上の論理CPUの数を取得するための静的な方法はありません。この数は、コンパイルと実行の間で簡単に変更できます。バイナリが別のシステムで実行されている場合

たとえば、CMake's ProcessorCountを使用して、コードをコンパイルするシステムの論理CPUの数を取得し、それを定義に入れることができます。

+0

いいね!私のプログラムでこの数字をあなたがすでに言ったような定義としてどのように使うことができますか? –

+0

私はそれを手に入れました。私は[リンク](https://cmake.org/cmake/help/latest/module/ProcessorCount.html)の例のようなスレッドの数を設定し、追加しました: 'set(CMAKE_CXX_FLAGS -DTHREADS = $ { N}) ' これをテンプレートで使用できます。ありがとうございました –

+0

うれしいことにうまくいきました。ちょっとしたヒント: 'add_definitions(-DTHREADS = $ {N}) 'を使うことができます。特に以前に設定されていた場合は、' CMAKE_CXX_FLAGS'を使いこなすよりも少し上品です。 – Zulan

1

私のテンプレートに利用できるスレッドの数を得るもう一つの静的な方法はありますか?

答えはstd::thread::hardware_concurrency()constexprの関数ではないので(それは絶対に論理的であるように、同時実行スレッド数が右、プログラムが動作するシステムに応じて異なる場合があります?)、NOですが、 num_threadsは、コンパイル時定数で初期化する必要があります。

あなたは、配列の代わりにstd::vectorを使用してのようないくつかの回避策を扱うかもしれません:

template <typename T> 
class SomeClass { 
public: 
    SomeClass() 
     : values(std::thread::hardware_concurrency()) 
    {} 

private: 
    std::vector<T> values; 
}; 
+1

無関係のビット。 std :: hardware_concurrency'(http://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency)は 'constexpr'ではなく' 'std :: hardware_concurrency''(' 'std :: hardware_concurrency'') :: hardware_constructive_interference_size'](http://en.cppreference.com/w/cpp/thread/hardware_destructive_interference_size)は 'constexpr'です。 – WhiZTiM

+0

@WhiZTiMそれは実際には非常に**合理的です。 '..interferanace_size' 1)は、メモリレイアウトを制御する主な用途のためにコンパイル時でなければなりません。 'alignas'と一緒に。 2)はコンパイル時に実際にはいくらか確実に決定できます。http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0154r0.html – Zulan

関連する問題