小编Hen*_*ann的帖子

std::thread 在模板函数之外调用模板函数

我正在尝试从模板函数创建线程,为线程提供另一个模板函数。

我附加了一个出现相同错误的情况的示例。为线程提供一个非模板化的函数(即此处一个 withint和一个 with float)不会导致错误。但是,由于我计划将此函数与许多不同类型一起使用,因此我不想指定模板类型。我还尝试了几种模板类型的指定(例如std::thread<T>std::thread(function<T>),但没有成功。

问题:如何使用模板函数std:thread外调用模板函数?

以下是该情况的最小编译示例,实际上模板是自己的类:

#include <thread>
#include <string>
#include <iostream>

template<class T>
void print(T* value, std::string text)
{
   std::cout << "value: " << *value << std::endl;
   std::cout << text << std::endl;
}

template<class T>
void threadPool(T* value)
{
   std::string text = "this is a text with " + std::to_string(*value);
   std::thread(&print, value, text);
}

int main(void)
{
   unsigned int a = 1;
   float b = 2.5;
   threadPool<unsigned int>(&a); …
Run Code Online (Sandbox Code Playgroud)

c++ templates c++11 stdthread

2
推荐指数
1
解决办法
2311
查看次数

标签 统计

c++ ×1

c++11 ×1

stdthread ×1

templates ×1