mch*_*hen 3 c templates cuda gpgpu thrust
我正在编写一个matrix模板类,可以打印到两个文件std::cout,即:
matrix<float> myMat;
...
myMat.cout(...) // print to std::cout
myMat.write("out.txt") // print to file
Run Code Online (Sandbox Code Playgroud)
两者都将共享一个共同的底层打印功能,我也试图将其作为模板实现,因为我已经看到了用于thrust::copy向两者std::cout和文件写入数据的不同示例.
下面是我所做的骨架,但它目前正在输出垃圾.任何人都可以指出我可能犯的一些错误吗?例如,我允许这样传球std::cout吗?
template <typename data_T> matrix {
...
template <typename out_T> int printTo(out_T &out, ...) {
data_T *start = ..., *end = ...;
...
thrust::copy(start, end, std::ostream_iterator<data_T>(out, " "));
...
}
int cout(...) {
...
printTo(std::cout, ...);
...
}
int write(char* path, ...) {
...
std::ofstream file;
file.open(path);
printTo(file, ...);
...
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
int printTo(std::ostream &out, ...) {...}无法解决问题.thrust::device_vector<T>,说dvec,并将其转换为一个data_T指针pvec使用thrust::raw_pointer_cast(&dvec[0])(因为CUBLAS库使用原始指针).然后我操作pvec然后想要打印出来.thrust::device_vector直接从原始指针打印(即*dvec),它确实有效:thrust::copy((*dvec).begin(), (*dvec).begin() + n ...).那么为什么我只能使用*dvec迭代器而不是原始指针强制转换pvec?不要raw_pointer_cast在这里使用.这会欺骗Thrust认为你有一个指向主机上数据的指针,这就是为什么你的代码没有给你你期望的.我原以为你的代码会崩溃.
要将a复制device_vector到a ostream_iterator,只需thrust::copy直接使用:
thrust::device_vector<float> vec = ...
thrust::copy(vec.begin(), vec.end(), std::ostream_iterator<float>(std::cout, " "));
Run Code Online (Sandbox Code Playgroud)