【问题标题】:Protected template member functions in a template class [duplicate]模板类中受保护的模板成员函数[重复]
【发布时间】:2016-04-06 00:42:54
【问题描述】:

假设我们有

template<typename T>
class Base
{
    ...

    protected:

        template<typename U>
        void compute(U x);

    ...
};

现在我想从派生类调用这个方法。对于非模板成员函数,我通常会使用using ... 声明或使用this-&gt;... 访问成员。但是,不清楚如何访问模板成员:

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

    ...
};

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    更容易。你可以写:

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

    类型是自动推断的。

    编辑

    对于一般情况,当无法推断类型时,可以使用:

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

    或者:

    this->template compute<float>();
    

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

    【讨论】:

    • 谢谢,但是一般情况下不能自动推断呢?我举了一个玩具例子,不幸的是,在我的例子中它没有推断出模板参数。
    猜你喜欢
    • 2020-04-13
    • 2011-04-29
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 2010-12-22
    相关资源
    最近更新 更多