繁体   English   中英

将带有模板参数的模板化函数与要模板化的类一起使用时出错

[英]Error in using templated function with template parameter to be templated class

这是一个最小的例子

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM