bikashamit
bikashamit

Reputation: 91

just returning non type parameter

I just learned compile-time array declaration via template, with the non-type parameter. so in this approach, we pass constant and array with size gets declared. like

#include<iostream>
using namespace std;

template<int size_of_array>
class arr 
{
public:
    int  arr[size_of_array];

    int size_of() { return size_of_array;   }
};

int main() 
{
    arr<4> arr1;
    cout << arr1.size_of();

    return 0;
}

Can we do something like variable value assigning at run time like if we remove arr[] from there. like

#include<iostream>
using namespace std;

template<int size_of_array>
class arr 
{
public:
    int  size_of_array;
    int size_of() { return size_of_array;   }
};

int main() 
{
    arr<4> arr1;
    cout << arr1.size_of();

    return 0;
}

Can we do that? or why not? Then maybe there is some thing about an array and a variable declaration which i don't know. Thank you in advance.

Upvotes: 0

Views: 101

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

Absolutely! You can expose the template parameters by writing a function to pass them through.

Your attempt only failed because:

  • you tried to re-use the template argument name for a data member name, and
  • you never actually assigned a value to the data member.

There's really no need for an additional data member here anyway, as the template argument is accessible throughout the class definition.

So, for a non-type template parameter like yours, just:

template <int size_of_array>
class arr 
{
public:
    static int size_of() { return size_of_array; }
};

Now arr<42>::size_of() is 42!

(I've made it static, not because you need to, but because in this example it makes sense; you could alternatively make it a non-static but const member function.)

And for a type:

template <typename T>
class arr 
{
public:
    using array_size_t = T;
};

Now arr<T>::array_size_t is the type T!

Upvotes: 3

Related Questions