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,855 questions

51,776 answers

573 users

How to use default arguments 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
#define DEFAULT_SIZE 6

template <class T = int, int size = DEFAULT_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();

	Test<> iobj2;
	for (int i = 0; i < DEFAULT_SIZE; i++)
		iobj2[i] = i + 5;
	iobj2.print();

	Test<> iobj3;
	iobj3.print();

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

	dobj.print();
}



/*
run:

3 4 5 6 7
5 6 7 8 9 10
2 3 4 5 6 7
0.2 0.4 0.6 0.8

*/

 



answered Mar 15, 2018 by avibootz
edited Apr 5, 2024 by avibootz

Related questions

1 answer 114 views
1 answer 139 views
2 answers 249 views
1 answer 196 views
1 answer 169 views
1 answer 134 views
134 views asked Dec 10, 2020 by avibootz
2 answers 218 views
...