Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Instance of C++ template class as a member of another template class

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading