0

I'm trying to do something like this for a project...

template <class N> class MyClass { float properties[N]; };

Is there anyway to accomplish this in C++?

Niall C.
  • 10,878
  • 7
  • 69
  • 61
David Carpenter
  • 1,389
  • 2
  • 16
  • 29
  • 1
    Not clear to me what you are expecting. An array of floats indexed by "some random class" ? - I'd say no you can't do that (but them I'm not up on the latest and greatest standards ;-). I'd say you'd need to create your own data structure for this rather relying on the native arrays. – John3136 Feb 27 '12 at 01:40
  • normally i would but this is a bit performance intensive – David Carpenter Feb 27 '12 at 01:56

1 Answers1

5

What you need is called value template parameter:

template <size_t N> class MyClass { float properties[N]; };
        //^^^^^^ note this 

Now you can instantiate this class template, passing any non-negative integral value as template argument. For example,

MyClass<10> c1;  //N=10
MyClass<100> c1; //N=100

You can pass const expression also as:

const size_t size = 200;
MyClass<size>  c2; //N=200
Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • thanks! thats what i needed for the header but now i cant get the .cpp file to compile properly, when i try and put any functions int the class MSVC is telling me "use of class template requires template argument list". any idea why? – David Carpenter Feb 27 '12 at 01:55
  • @DavidCarpenter: How would I know what is `.cpp` file? and what does it contain? – Nawaz Feb 27 '12 at 02:14
  • the implementation of member functions for MyClass, like a constructor but visual studio highlights them with that error – David Carpenter Feb 27 '12 at 02:15
  • @DavidCarpenter: Implementation of a templates should go in the header file itself, or else it wouldn't compile. So define the class template in the header file. Read this : http://stackoverflow.com/questions/1724036/splitting-templated-c-classes-into-hpp-cpp-files-is-it-possible – Nawaz Feb 27 '12 at 02:17
  • the template is in the header, but the matching cpp files is giving me the error – David Carpenter Feb 27 '12 at 02:18
  • @DavidCarpenter: Did you define the member functions in the header file? What is "matching" cpp files? – Nawaz Feb 27 '12 at 02:18
  • @DavidCarpenter: Read this : http://stackoverflow.com/questions/1724036/splitting-templated-c-classes-into-hpp-cpp-files-is-it-possible – Nawaz Feb 27 '12 at 02:18
  • so the only way to do it is to write the functions right into the header? – David Carpenter Feb 27 '12 at 02:22
  • @DavidCarpenter: Yes. That is simple! – Nawaz Feb 27 '12 at 02:36