The problem is that you are trying to initialize the same member variable with different data types. This will not work the way you currently have your code, as the entire function will be created, regardless of the type used. When the template parameter T
is int
, the function tries to assign the rows to an array. when the template parameter T
is a string, the function tries to assign integers to the array.
To get around this, you can use the specialization and split it into two different functions and let the compiler instantiate the correct one based on the template parameters.
template <> void TWO <string, 12>::ReadData() { a[0] = "Jan"; a[1] = "Feb"; a[2] = "Mar"; a[3] = "Apr"; a[4] = "May"; a[5] = "Jun"; a[6] = "Jul"; a[7] = "Aug"; a[8] = "Sep"; a[9] = "Oct"; a[10] = "Nov"; a[11] = "Dec"; } template <> void TWO <int, 10>::ReadData() { srand(time(0)); for (int i = 0; i < 10; i++) { a[i] = rand() % 20; } }
Keep in mind that if the template parameters do not exactly match the available specialization, you will receive a link time error. If you are using C ++ 11, you can make this more obvious by using static_assert
in a non-specialized version of a function
template <class T, int n> void TWO <T, n>::ReadData() { static_assert(0, "Specialization not available"); }
This will result in a compile-time error if the template parameters are not <int, 10>
or <string, 12>
.
Also, as pointed out in the comments, you should put the srand
call in main
instead of the ReadData
function.
source share