gpt4 book ai didi

c++ - 如何使用模板类作为函数的参数?

转载 作者:行者123 更新时间:2023-11-27 22:34:54 26 4
gpt4 key购买 nike

我想要使用模板类参数的线程,但我不知道如何使用模板类作为线程方法的参数。

我已经尝试在模板类中创建方法,但我不想这样做。人们一般不使用这种解决方案。

//....
//Linked List code
//.....


void func1(slist<T> s){
for (int i = 0; i < 1000; i++) {
s.push_(i);
}
} // this part is problem of my code.

int main() {
int i;
slist<int> s;
thread t1(func1,s); //Compile error.
func1(s); // here, too.

return 0;
}

我期望线程与链表竞争的结果。

最佳答案

通用解决方案:

template<typename T>
void func1(slist<T>& s){
for (int i = 0; i < 1000; i++) {
s.push_(i);
}
}

或者您可以专注于一种特定类型:

void func1(slist<int>& s){
for (int i = 0; i < 1000; i++) {
s.push_(i);
}
}

(另请注意,您可能希望传递对列表的引用,而不是拷贝)

关于c++ - 如何使用模板类作为函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55963926/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com