0

I use template to deduce required static array length. Header file looks like:

template<uint8_t LENGTH>
class Foo
{
   int array[LENGTH];
   Foo();
}

I want to use LENGTH value in constructor definition in cpp file, somewhat similiar to:

Foo::Foo()
{
   for(uint8_t i = 0; i < LENGTH; i++)
   {
      //do_stuff
   }
}

So far I've done this by assigning LENGTH value to another variable in header file. How can I do this?

412131
  • 91
  • 6

2 Answers2

1

You can't separate templates into a header file and a source file, the whole thing needs to be implemented in the header file. If you want to know why, you can read this question. So you need to implement the whole thing in the header file:

template<uint8_t length>
class Foo{
private:
    int array[length];

public:
    Foo(){
        for(uint8_t i = 0; i < length; i++){
            //do_stuff
        }
    }
};

If you do this, you won't have any problem using length in the constructor.

Also note that you forgot the ; at the end of the class definition. That's a mistake that could cause a compiler error. Also, it's best to use entirely upper-case names only for macros, so I called it length instead of LENGTH. I also suggest that you explicitly say if attributes and methods are public or private by adding public: or private:. By default, they're always private.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
0

To iterate through an entire array in C++ 11, just use:

for(auto &it: array){
    // do stuff
}
saladguy
  • 75
  • 1
  • 1
  • 7
  • Thanks, this will do for example I gave, but reason I want exact value is I need to do some calculation based on it, not only as an iterator. – 412131 Aug 23 '17 at 09:22