这是一个简单的例子
#include <iostream>
template<typename T>
struct MyClass{
T value;
};
template<typename T, template<typename> class Class>
void foo(Class<T>& myClass){
myClass.value=0;
};
int main(){
MyClass<double> myclass;
foo<double, MyClass<double>>(myclass);
return 0;
}
这段代码不会编译并给出错误
error: no instance of function template "foo" matches the argument list
argument types are: (MyClass<double>)
foo<double, MyClass<double>>(myclass);
之所以要写一个函数,是因为我想写一个在CPU和GPU之间传输数据的函数。函数看起来像
template<typename Scalar, template<typename > class Host,
template<typename> class Device>
void copyFromHostAsync(const Host<Scalar> &host, Device<Scalar> &device, cudaStream_t stream) {
assert(host.rows() == device.rows());
assert(host.cols() == device.cols());
cudaMemcpyAsync(device.getPtr(), host.getPtr(), sizeof(Scalar) * host.rows() * host.cols(),
cudaMemcpyHostToDevice, stream);
}
我想使用模板化类作为参数,以便底层标量类型相同。
欢迎任何帮助。
最佳答案
foo
是一个模板函数,它将一个类型 T
和一个具有 1 个参数类型 MyClass
的模板类型作为模板参数。
如果你写:
foo<double, MyClass<double>>(myclass);
第二个模板参数不是具有 1 个参数类型的模板。它只是一个简单的类型。因为它是一种类型,而不是模板类型,所以您的代码无法编译。
只使用 MyClass
将编译,因为 MyClass
是一个模板类型,它接受 1 个模板参数:
foo<double, MyClass>(myclass);
此外,让编译器为您完成工作并推导类型:
foo(myclass);
关于c++ - 使用带有模板参数的模板函数作为模板类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40809912/