2016-11-05 55 views
0

我有两个文件 - 一个是我将一个无符号参数传递给模板,另一个包含模板声明和定义。如何将无符号参数传递给模板?

/*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;行引发错误,只接受const值。有什么办法可以将n的值传递给ThreadCount

编辑:我希望线程的大小在编译时间后可以改变。

+0

为什么不直接使用一个构造函数的参数? –

+0

@Jim如果你可以在上面的示例中提供一个小例子,那将会很好。 – Scissor

+1

@JimV'std :: array'需要编译时间常量大小。 – user4581301

回答

1

模板参数和std::array的大小必须在编译时已知,以便编译器可以生成正确的代码。

选项:

静态大小的一切。一切都在编译时设置,不能在运行时更改。 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,在threadpool构造函数的参数,以及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); 
} 
+0

谢谢。由此解决。 – Scissor

0

不,你不能通过n在你的情况。在C++中,模板是静态编译的。所以它的参数必须是编译时间常量。所以constexpr unsigned n = 10;将使编译器很高兴,但我不那么想。

但是,如果您使用C99,它有一个称为可变长度数组的特性(在C11中它变成可选),它允许您声明一个具有运行时大小的数组。

+0

可变长度数组可由编译器扩展在某些C++编译器中使用,但不推荐使用。由于并非所有的编译器都支持VLA,并且支持它们的方式不同,因此移植性有限。也损坏'sizeof'的编译时''const''s – user4581301

相关问题