作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我再次需要您的帮助,使 std::thread
与模板对象一起工作。这次我的问题是在其中一个论点中。
我尝试将对虚拟类的(有效)实例化的引用作为我的线程的参数之一传递,但它不起作用。请注意,传递指针而不是引用可以解决所有问题。但是,为什么我不能给出引用(我更喜欢,原因有很多)
重现我的错误的小代码:
#include <cstdio>
#include <thread>
#include <vector>
template<typename T>
class functor { public: virtual T operator()(T) const = 0; };
template<typename T>
class square : public functor<T>
{
public:
T operator()(T f) const { return f*f; }
};
template<typename T>
void thread(const functor<T>& func, size_t imin, size_t imax) // line1
{
for(size_t i=imin; i<imax; ++i)
{
T arg = T(i);
std::cout << arg << "=>" << (func)(arg)) << std::endl; // line2
}
}
template<typename T>
void threadlauncher(const functor<T>& func, size_t imin, size_t imax, size_t nbthread)
{
size_t window = (imax-imin)/nbthread + ((imax-imin)%nbthread?1:0);
std::vector<std::thread> threads;
for (size_t idthread=0; idthread<nbthread; ++idthread)
{
size_t tmin = std::min(window*(idthread+0), imax);
size_t tmax = std::min(window*(idthread+1), imax);
threads.push_back(
std::thread(&thread<T>, func, tmin, tmax) // line3
);
}
for (std::thread& thread : threads)
thread.join();
}
int main()
{
square<float> func;
threadlauncher<float>(func, 0, 10, 3);
return 0;
}
编译器 (gcc 4.9.2) 告诉我我的对象无效,因为 operator()
在 threadlauncher
中是虚拟的
请注意,更改代码以使用指针传递线程的参数可以解决此问题
void thread(const functor<T>* func, size_t imin, size_t imax) // line1
std::cout << arg << "=>" << (*func)(arg)) << std::endl; // line2
std::thread(&thread<T>, &func, tmin, tmax) // line3
我怎样才能让他明白我的推荐是有效的?
我从编译器收到一条长长的/不可读的错误消息。我想重要的部分是
src/functorthreads.cc:50:38: required from here
/usr/include/c++/4.9.2/functional:1713:9: erreur: invalid abstract parameter type ‘functor<float>’
__type;
^
src/functorthreads.cc:6:7: note: because the following virtual functions are pure within ‘functor<float>’:
class functor
^
src/functorthreads.cc:9:13: note: T functor<T>::operator()(T) const [with T = float]
virtual T operator()(T) const = 0;
最佳答案
std::thread
获取其参数的拷贝。函数的参数是一个引用并不重要.... thread
构造函数仍将复制参数,因为它们被传递给另一个线程。这就是指针起作用的原因,因为它们正在被复制。
如果您知道您的对象将在线程的整个生命周期内保持在范围内,您可以使用 std::ref
来包装您的参数:
std::thread(&thread<T>, std::ref(func), tmin, tmax)
关于c++ - 将对虚类实现的引用作为线程参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27231741/
我有一个特别的问题想要解决,我不确定是否可行,因为我找不到任何信息或正在完成的示例。基本上,我有: class ParentObject {}; class DerivedObject : publi
在我们的项目中,我们配置了虚 URL,以便用户可以在地址栏中输入虚 URL,这会将他们重定向到原始 URL。 例如: 如果用户输入'http://www.abc.com/partner ',它会将它们
我是一名优秀的程序员,十分优秀!