尝试编译时
template<typename type,const char* format>__device__ void d_prettyPrintVector(type* v, const unsigned int size)
{
printf("\n ");
for(int i=0; i<size; i++)
printf(format, v[i]);
}
template<> void d_prettyPrintVector<float, "%4.1f ">(float*, const unsigned int);
template<> void d_prettyPrintVector<int, "%2d " >(int*, const unsigned int);
template<> void d_prettyPrintVector<char, "%2d " >(char*, const unsigned int);
template<> void d_prettyPrintVector<bool, "%d" >(bool*, const unsigned int);
然后像这样使用它
d_prettyPrintVector(dc, blockDim.x);
我得到了
kernels.cu(104): error: no instance of function template "d_prettyPrintVector" matches the argument list
argument types are: (int *, const unsigned int)
怎么了?
最佳答案
我认为您不清楚如何使用类型、float
、int
等来获取适当的格式字符串。
你可以重新设计你的函数看起来像这样:
template <typename type>
void d_prettyPrintVector(type* v, const unsigned int size)
{
printf("\n");
for(int i=0; i<size; i++)
printf(getFormatString<type>(), v[i]);
// ^^^ Get an format string appropriate for the type.
}
如果你有一个函数模板,那将是完全有效的代码:
template <typename type> char const* getFormatString();
对您感兴趣的类型进行了专门化。换句话说,以下内容应该有效:
template <typename type> char const* getFormatString();
template <typename type>
void d_prettyPrintVector(type* v, const unsigned int size)
{
printf("\n");
for(int i=0; i<size; i++)
printf(getFormatString<type>(), v[i]);
// ^^^ Get an format string appropriate for the type.
}
template <> char const* getFormatString<float>() { return "%4.1f "; }
template <> char const* getFormatString<int>() { return "%2d "; }
template <> char const* getFormatString<char>() { return "%2d "; }
template <> char const* getFormatString<bool>() { return "%1d "; }
现在,您可以使用:
int a[] = {1, 2};
d_prettyPrintVector(a, 2);
float b[] = {1.1f, 2.2f};
d_prettyPrintVector(b, 2);
没有任何问题。
额外
您可以扩展该想法以提供一个 lambda 函数作为 d_prettyPrintVector
的参数。 lambda 函数可以返回更适合单个用例的自定义格式字符串。
重载 d_prettyPrintVector
。提供一个可以将 lamba 函数作为参数的函数。
template <typename type, typename Format>
void d_prettyPrintVector(type* v, const unsigned int size, Format format)
{
printf("\n");
for(int i=0; i<size; i++)
printf(format(), v[i]);
}
您甚至可以使用新函数实现初始函数,这样您就不必重复打印项目的细节。
template <typename type> char const* getFormatString();
template <typename type>
void d_prettyPrintVector(type* v, const unsigned int size)
{
d_prettyPrintVector(v, size, [](){return getFormatString<type>();});
}
现在,除了之前调用打印 a
和 b
之外,您现在还可以使用:
// Define the format on the fly, using a lambda function.
d_prettyPrintVector(a, 2, []() -> char const* {return "%4d ";});
// Define the format on the fly, using a lambda function.
d_prettyPrintVector(b, 2, []() -> char const* {return "%.6f ";});
关于c++ - 没有函数模板的实例与参数列表匹配(试图打印数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29000987/