简体   繁体   中英

C++ templated, statically allocated array

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++?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM