Ran Wang Ran Wang - 1 year ago 67
C++ Question

Error in using templated function with template parameter to be templated class

here is a minimal example

#include <iostream>

template<typename T>
struct MyClass{
T value;

template<typename T, template<typename> class Class>
void foo(Class<T>& myClass){

int main(){
MyClass<double> myclass;
foo<double, MyClass<double>>(myclass);
return 0;


This code will not compile and gives the error

error: no instance of function template "foo" matches the argument list
argument types are: (MyClass<double>)
foo<double, MyClass<double>>(myclass);

The reason why I want to write a function is that I want to write a function that transfer data between CPU and GPU. The function looks like

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


I want to use the templated class as parameter so that the underlying scalar type is the same.

Any help is welcomed.

Answer Source

foo is a template function, which takes as template parameter a type T, and a template type with 1 argument type MyClass.

If you write:

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

The second template parameter is not a template with 1 parameter type. It is just a simple type. And because it is a type, not a template type, your code doesn't compile.

Using just MyClass will compile, as MyClass is a template type which takes 1 template parameter:

foo<double, MyClass>(myclass);

Also, just let the compiler do the job for you and let it deduce the types:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download