&#39;使用Base <t> :: func()&#39;在派生类中使得&#39; func&#39;在派生类之外无法访问

时间:2017-06-26 18:30:39

标签: c++ templates

这是C ++。我有以下程序:

#include <iostream>

using namespace std;

template <typename T>
class Base {
public:
    T t;
    void use() {cout << "base" << endl;};
};

template <typename T>
class Derived: public Base<T> {
using Base<T>::use;

public:
   T x;
   void print() { use(); };

};

using namespace std;

int main() {

    Derived<float> *s = new Derived<float>();

    s->Base<float>::use(); // this is okay
    s->use();  // compiler complaints that "void Base<T>::use() is inaccessible"

    s->print(); // this is okay

    return 0;
}

Base :: use()不使用模板类型名称T.根据Why do I have to access template base class members through the this pointer?,我使用&#39;使用Base :: use&#39;在Derived中,我可以将其称为&#39;使用&#39;在Derived :: print()中。但是,我不能通过指向Derived的指针调用use()。会导致这种情况的原因是什么?

1 个答案:

答案 0 :(得分:5)

你需要有一行

using Base<T>::use;

public的{​​{1}}部分。

Derived

Live demo