Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,994 questions

51,939 answers

573 users

How to template class in C++

1 Answer

0 votes
#include <iostream>

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

#define SIZE 3

template <class T> class Test {
	T arr[SIZE];
public:
	Test(void)
	{
		for (int i = 0; i < SIZE; i++)
			arr[i] = i + 2;
	}
	T &operator[](int i);
	void print(void)
	{
		for (int i = 0; i < SIZE; i++)
			cout << arr[i] << " ";
		cout << endl;
	}
};

template <class T> T &Test<T>::operator[](int i)
{
	if (i < 0 || i > SIZE - 1)
		cout << "index " << i << " out of range" << endl;
	
	return arr[i];
}



int main()
{
	Test<int> int_array;
	Test<float> float_array;

	int_array.print();
	for (int i = 0; i < SIZE; i++)
		int_array[i] = i + 111;
	int_array.print();
	int_array[5] = 9999;

	float_array.print();
	for (int i = 0; i < SIZE; i++)
		float_array[i] = (float)i / 6 + 2;
	float_array.print();
	float_array[6] = 3.14;
	
	return 0;
}


/*
run:

2 3 4
111 112 113
index 5 out of range
2 3 4
2 2.16667 2.33333
index 6 out of range

*/

 



answered Mar 13, 2018 by avibootz

Related questions

1 answer 118 views
1 answer 111 views
1 answer 108 views
1 answer 124 views
1 answer 139 views
139 views asked Dec 10, 2020 by avibootz
1 answer 186 views
2 answers 253 views
...