模板类中受保护的模板成员函数

Protected template member functions in a template class

本文关键字:成员 函数 受保护      更新时间:2023-10-16

假设我们有

template<typename T>
class Base
{
    ...
    protected:
        template<typename U>
        void compute(U x);
    ...
};

现在我想从派生类中调用这个方法。对于非模板成员函数,我通常使用using ...声明或使用this->...访问成员。然而,目前尚不清楚如何访问模板成员:

template<typename T>
class Derived : public Base<T>
{
    // what's the correct syntax for
    // using ... template ... Base<T>::compute<U> ... ?
    ...
    void computeFloat()
    {
        float x = ...;
        compute<float>(x);
    }
    void computeDouble()
    {
        double x = ...;
        compute<double>(x);
    }
    ...
};

更简单。你可以写:

void computeFloat() {
    float x = .1;
    this->compute(x);
}

类型是自动推导的。

编辑

对于一般情况,当无法推导类型时,可以使用以下任一选项:

Base<T>::template compute<float>();

或者:

this->template compute<float>();

对于这些示例,我使用了一个不带参数的compute函数。