Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Hostgator 1 Penny

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Distribute your Resume to 500+ Job Boards & Recruiters


7,372 questions

10,373 answers

573 users

How to use non-type argument with template class in C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

#define SIZE_INT 5
#define SIZE_DOUBLE 4

template <class T, int size> class Test {
private:
	T arr[size]; 
public:
	Test() {
		for (int i = 0; i < size; i++) 
			arr[i] = i + 2;
	}
	T &operator[](int i);
	void print(void);
};

template <class T, int size>
T &Test<T, size>::operator[](int i)
{
	if (i < 0 || i > size - 1) {
		cout << "index: " << i << " is out of range" << endl;
		return arr[size - 1];
	}
	return arr[i];
}
template <class T, int size>
void Test<T, size>::print(void)
{
	for (int i = 0; i < size; i++)
		cout << arr[i] << ' ';
	cout << endl;
}

int main()
{
	Test<int, SIZE_INT> iobj1;
	for (int i = 0; i < SIZE_INT; i++)
		iobj1[i] = i + 3;
	iobj1.print();
	iobj1[33] = 80;

	Test<int, SIZE_INT> iobj2;
	iobj2.print();

	Test<double, SIZE_DOUBLE> dobj;
	for (int i = 0; i < SIZE_DOUBLE; i++)
		dobj[i] = (double) (i + 1) / 5;
	dobj.print();

	return 0;
}


/*
run:

3 4 5 6 7
index: 33 is out of range
2 3 4 5 6
0.2 0.4 0.6 0.8

*/

 




answered Mar 15 by avibootz
...