在c++中,专门化被视为重载

specialization being seen as overloading in C++

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

我是模板化编程的初学者。

我在模板类中有三个模板函数:

// initialize the model (generic template for any other type)
template <typename ImgDataType>
void GrimsonGMMGen<ImgDataType>::InitModel(const cv::Mat& data) // data is an rgb image
{ ... }
template<>
void GrimsonGMMGen<cv::Vec3b>::InitModel(const cv::Mat& data)
{...}
template<>
void GrimsonGMMGen<float>::InitModel(const cv::Mat& data)
{ ... }

但是我得到一个错误说有重声明指向重声明in我记得以前使用过这样的专门化,效果很好。我哪里做错了?

我需要特殊化它们,因为我正在设置的一些数据结构需要我正在使用的图像类型的信息。

您在问题中尝试做的事情绝对有效:类模板的成员函数可以单独特化(完全)。例如:

#include <iostream>
template <typename T> struct Foo
{
    void print();
};
template <typename T> void Foo<T>::print()
{
    std::cout << "Generic Foo<T>::print()n";
}
template <> void Foo<int>::print()
{
    std::cout << "Specialized Foo<int>::print()n";
}
int main()
{
    Foo<char> x;
    Foo<int>  y;
    x.print();
    y.print();
}

现场演示