如何重载另一个模板类型的模板类方法

How to overload template class method for another template type?

本文关键字:类型 类方法 另一个 何重载 重载      更新时间:2023-10-16

在不使用Boost的情况下,c++ 03中的标准方法是什么?

  1. 重载模板类方法,模板类型只出现在方法的返回值中,或者
  2. 为另一个模板化类型专门化一个模板类方法。

换句话说,这是如何工作的:

template <typename T, int N> struct Vector { T x[N]; };
struct Sampler
{
    template <typename T>
    T next() {
        // Do some work and return a value of type T.
        return T();
    }
    template <typename T, int N>
    Vector<T, N> next() {
        // Do some different work and return a value of type Vector<T, N>.
        return Vector<T, N>();
    }
};
int main() {
    Sampler sampler;
    sampler.next<double>();
    sampler.next<Vector<float, 2> >();
    return 0;
}

如前所述,next()的两次使用都调用第一个方法,而我希望第二次使用调用第二个方法。

看起来您要求对模板函数进行部分专门化。语言中没有这个功能,但是您可以使用标记调度或类模板来模拟它。下面是一个使用标签调度的例子:

template <typename T> struct tag{};
struct Sampler
{    
    template <typename T>
    T next() {
        return next(tag<T>());   
    }
private:
    template <typename T>
    T next(tag<T>) {
        return T();
    }
    template <typename T, int N>
    Vector<T, N> next(tag<Vector<T,N> >) {
        return Vector<T, N>();
    }
};

然后像这样使用:

sampler.next<double>();
sampler.next<Vector<double,2> >();

现场演示

请注意,在c++ 11之前的第二行最后一个> >标记之间需要一个空格。

可以使用helper结构体:

template<typename T>
struct SamplerHelper
{
    T operator()() const 
    {
        std::cout << "Tn";
        return T();
    }
};
template<typename T, int N>
struct SamplerHelper<Vector<T, N> >
{
    Vector<T, N> operator()() const 
    {
        std::cout << "vecn";
        return Vector<T, N>();
    }
};
struct Sampler
{
    template <typename T>
    T next() {
        return SamplerHelper<T>()();
    }
};