[英]Partial specialization in c++ template
I have a template class to print out the elements in vector. 我有一个模板类来打印向量中的元素。 I have both for pointer and reference version.
我有指针和参考版本。
// HEADER
class Util {
...
template <class T>
static void print(const std::vector<T>* vectorArray);
template <class T>
static void print(const std::vector<T>& vectorArray);
...
static void printByteStream(const std::vector<unsigned char>& input);
...
};
// BODY
template <class T>
void Util::print(const std::vector<T>* vectorArray)
{
for (auto i = vectorArray->begin(); i != vectorArray->end(); ++i)
{
std::cout << *i << ":";
}
std::cout << std::endl;
}
template <class T>
void Util::print(const std::vector<T>& vectorArray)
{
return Util::print(&vectorArray);
}
template void Util::print(const std::vector<int>* vectorArray);
template void Util::print(const std::vector<std::string>* vectorArray);
template void Util::print(const std::vector<int>& vectorArray);
template void Util::print(const std::vector<std::string>& vectorArray);
I also have a print code for byte stream. 我还有一个字节流的打印代码。
void Util::printByteStream(const std::vector<unsigned char>& input)
{
for (auto val : input) printf("\\x%.2x", val);
printf("\n");
}
I want to teach the C++ compiler that when I call print with T == unsigned char, call the printByteStream with partial specialization. 我想教C ++编译器,当我用T == unsigned char调用print时,调用具有部分特化的printByteStream。
I added this code in the body. 我在体内添加了这段代码。
void Util::print(const std::vector<unsigned char>& vectorArray)
{
return Util::printByteStream(vectorArray);
}
When compiled, the C++ compiler complains that it can't find matching code. 编译时,C ++编译器抱怨它无法找到匹配的代码。 What might be wrong?
可能有什么问题?
error: prototype for 'void Util::print(const std::vector<unsigned char>&)' does not match any in class 'Util'
void Util::print(const std::vector<unsigned char>& vectorArray)
I think you need to add an empty template 我想你需要添加一个空模板
template <>
void Util::print(const std::vector<unsigned char>& vectorArray)
{
return Util::printByteStream(vectorArray);
}
I have to check. 我得检查一下。 I don't have VS on this computer though.
我在这台电脑上没有VS.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.