0

Here's my code:

#include <iostream>

struct Plot {
    float test;
    
    Plot() : test(1.0f) {
    }
};

template <class T>
struct PlotTest : Plot {
    T *pModule;
    
    PlotTest(T *module) : Plot(), pModule(module) {

    }
};

template <class T>
struct PlotTestCustom : PlotTest<T> {
    PlotTestCustom(T *module) : PlotTest<T>(module) {
        test = 2.0f;
    }
};

int main()
{

}

But when I compile, it seems that PlotTestCustom can't see the float test; variable (which is on the "main" parent).

Where am I wrong?

markzzz
  • 47,390
  • 120
  • 299
  • 507

3 Answers3

3

During name lookup with template, it won't look at the base class (there could be a specialization of PlotTest that does not inherit from Plot for instance).

Thus you will have to give the compiler a hint:

PlotTestCustom(T *module) : PlotTest<T>(module) {
    this->test = 2.0f;
}

It means delay lookup until instantiation by making it a dependent name.

Full example here:

#include <iostream>

struct Plot {
    float test;
    
    Plot() : test(1.0f) {
    }
};

template <class T>
struct PlotTest : Plot {
    T *pModule;
    
    PlotTest(T *module) : Plot(), pModule(module) {
        test = 3.0; // accessible Plot is not a dependent base class
    }
};

// specialization that does not inherit
template<>
struct PlotTest<int> {
};

template <class T>
struct PlotTestCustom : PlotTest<T> {
    PlotTestCustom(T *module) : PlotTest<T>(module) {
        this->test = 2.0f;
    }
};

int main()
{
    double d{};
    int i{};
    PlotTestCustom<double> p1{&d};
    //PlotTestCustom<int> p2{&i}; -> does not compile
}
nop666
  • 585
  • 2
  • 6
1

test is not a dependent name here, so you have to access it through this pointer thus deferring actual lookup until the template parameter is known

coliru

nvevg
  • 180
  • 1
  • 9
1

You have to give compiler a hint, in what part of your object this member can be found:

template <class T>
struct PlotTestCustom : PlotTest<T> {
    PlotTestCustom(T *module) : PlotTest<T>(module) {
        Plot::test = 2.0f;
    }
};
bipll
  • 11,747
  • 1
  • 18
  • 32