Home > Enterprise >  Instance of C template class as a member of another template class
Instance of C template class as a member of another template class

Time:04-20

Let's say I have following templated C class

#include <cstdint>      

template <uint32_t NO_POINTS>
class A
{
public:
  struct Point
  {
    float x;
    float y;
  };

  A(const Point (&points)[NO_POINTS])
  {
      for (uint32_t point = 0; point < NO_POINTS; point  ) {
          table[point] = points[point];
      }
  }
  
private:
  Point table[NO_POINTS];
};

and I would like to use an instance of this class as a private member of the following class:

#include "A.h"

template <uint32_t NO_LUT_POINTS>
class B
{

public:
  B(A<NO_LUT_POINTS>::Point (&table)[NO_LUT_POINTS]) : lut(table){}

private:
  A<NO_LUT_POINTS> lut;
};

#include "B.h"

int main(int argc, char** argv) {

     B<4> foo({{1326.0, 25.0},   {1601.0, 30.0},   {1922.0, 35.0},   {2293.0, 40.0}});
           
    return 0;
}

I have attempted to compile this code but the compiler reports following error A<NO_LUT_POINTS>::Point is not a type. I don't understand what the reason for this error is. Can anybody explain to me why the compiler reports this error?

CodePudding user response:

This is a common mistake with types nested in template classes. You need to add typename to tell the compiler that Point is a type.

...
public:
  B(typename A<NO_LUT_POINTS>::Point const (&table)[NO_LUT_POINTS]) : lut(table){}
...

Beyond solving your problem, however, please notice that Point doesn't depend on the template parameters of A, so you should not nest it in that class. This would remove the necessity for adding typename.

  • Related