Array.h CLASS

#ifndef __ARRAY_H
#define __ARRAY_H

template <typename DataType, int size, DataType zero>
class Array
{
public:
	// set function, sets an index
	void Set(DataType p_item, int p_index)
	{
		m_array[p_index] = p_item;
	}

	// get function, gets the index
	DataType Get(int p_index)
	{
		return m_array[p_index];
	}

	// clear function
	void Clear(int p_index)
	{
		m_array[p_index] = zero;
	}

private:
	// the array
	// .. I declare an array of DataType with size, 
	// .. size which will never change
	DataType m_array[size];
};

#endif

mainDriver.cpp FILE

#include <iostream>

#include "Array.h"

using namespace std;

int main ()
{
	Array<int, 5, 42> iarray5;
	Array<int, 10, 30> iarray10;
	Array<float, 5, 0.0f> farray15;

	system("PAUSE");
	return 0;
}

It works fine when I use an integer type.
But the problem arises when I declare the Array<float, 5, 0.0f>
Errors:

Error	2	error C2133: 'farray15' : unknown size	
Error	3	error C2512: 'Array' : no appropriate default constructor available	
Error	1	error C2993: 'float' : illegal type for non-type template parameter 'zero'

the error is this: error C2993: 'float' : illegal type for non-type template parameter 'zero'
non-type template parameters are restricted to
a. constant integral values (including enumerations)
b. pointers or references to objects with external linkage.

the simplest work around is: take the parameter as an argument to the constructor.

template < typename DataType, int size >
class Array
{
  public:
    explicit Array( const DataType& z = DataType() ) : zero(z) {}
    // ...
    // ...
  private:
    DataType m_array[size];
    DataType zero ;
};

int main ()
{
  Array<int, 5> iarray5(42);
  Array<int, 10> iarray10(30);
  Array<float, 5> farray15(0.0f);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.