Scissor Scissor - 27 days ago 7
C++ Question

How to pass an unsigned argument to a template?

I have two files - One from which I am passing an unsigned argument to the template, another which contains the template declaration and definition.

/*File1.cc */
#include "File2.h"
int main()
{
unsigned n = 10;
ThreadPool<n> pool; //Error
.....
}




/* File_2.h */
....
namespace nbsdx {
namespace concurrent {

template <unsigned ThreadCount>
class ThreadPool {
std::array<std::thread, ThreadCount> threads;
....
};
}}


ThreadPool<n> pool;
line is throwing an error and only accepting a const value. Is there any way I can pass the n value to the ThreadCount?

EDIT: I want the size of the threads to be changeable after compile time.

Answer

Template arguments and std::array's size must be known at compile time so that the compiler can generate the correct code.

Options:

Static sizing of everything. Everything is set at compile time and can not be changed at runtime. Documentation on constexpr.

#include <array>
#include <thread>

template <unsigned ThreadCount>
class ThreadPool {
    std::array<std::thread, ThreadCount> threads;
};

int main()
{
    constexpr unsigned n = 10; // n is fixed at compile time and unchangable.
    ThreadPool<n> pool;  //Error
}

std::vector, a parameter on the threadpool constructor, and the Member Initializer List

#include <vector>
#include <thread>

class ThreadPool {
    std::vector<std::thread> threads;
public:
    ThreadPool(unsigned n): threads(n) // constructs threads with n elements
    {
    }
};

int main()
{
    unsigned n = 10;
    ThreadPool pool(n);
}
Comments