2016-11-25 53 views
1

这里是一个小例子,误差为模板类

#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); 

} 

我想使用模板类作为参数,以便底层标量类型是相同的。

欢迎任何帮助。

回答

2

foo是一个模板函数,它将模板参数的类型设为T,模板类型的参数类型为MyClass

如果你写:

foo<double, MyClass<double>>(myclass); 

第二个模板参数是 1个参数类型的模板。这只是一个简单的类型。由于它是一种类型,而不是模板类型,因此您的代码无法编译。

只需使用MyClass将编译,因为MyClass是一个模板类型这需要1个模板参数:

foo<double, MyClass>(myclass); 

而且,只是让编译器为你做的工作,让它推断类型:

foo(myclass); 
+0

确实是这样的先生!非常感谢你! –