c++模板的部分专门化

Partial specialization in c++ template

本文关键字:专门化 c++      更新时间:2023-10-16

我有一个模板类来打印vector中的元素。我有两个指针和引用版本。

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

我也有字节流的打印代码。

void Util::printByteStream(const std::vector<unsigned char>& input)
{
    for (auto val : input) printf("\x%.2x", val);
    printf("n");
}

我想教c++编译器,当我用T == unsigned char调用print时,用部分特化调用printByteStream。

我在正文中添加了这段代码。

void Util::print(const std::vector<unsigned char>& vectorArray)
{
    return Util::printByteStream(vectorArray);
}

编译时,c++编译器报错找不到匹配的代码。可能出了什么问题?

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)

我认为你需要添加一个空模板

template <>
void Util::print(const std::vector<unsigned char>& vectorArray)
{
    return Util::printByteStream(vectorArray);
}

我得查一下。我这台电脑上没有VS