I have some questions about the way in which Prata (C++ Primer Plus, pp. 756ff.) defines an array template which is supposed to show how you would use a template argument for array size (hence the int n). My questions have to do with the use of "explicit" and "virtual" in the prototypes. Here's the relevant part of the code:
Code:
template <class T, int n>
class ArrayTP
{
private:
T ar[n];
public:
ArrayTP() {};
explicit ArrayTP(const T & v);
virtual T & operator[](int i);
virtual T operator[](int i) const;
};
template <class T, int n>
ArrayTP<T, n>::ArrayTP(const T & v)
{
for (int i = 0; i < n; i++)
ar[i] = v;
}
template <class T, int n>
T & ArrayTP<T, n>::operator[](int i)
{
if (i < 0 || i >=n)
{
std::cerr << "Error in array limits: " << i
<< " is out of range\n";
std::exit(EXIT_FAILURE);
}
return ar[i];
}
First, as to the "explicit": This is to prevent unintended type conversions, right? But here, it would be converting a type to a type array, wouldn't it? Like, if T is double, then the explicit just prevents a double from being unintentionally converted into an array of doubles if you happen to make a mistake in naming your variables.
So, first question on that: Am I understanding the reasoning behind it correctly? If I am, this seems fairly paranoid even by my standards (and I tend to be pretty paranoid). Or is it just a good habit to write "explicit" on anything that could be an unwanted type conversion without giving a lot of thought to whether it's realistic or not (which, admittedly, is nearly impossible to anticipate in all cases).
Second, on the use of "virtual" for the indexing operators (the const version is the same as the one in the above code): That seems to be an invitation to modify this definition in any derived class. But, aside from the error messages, which are certainly up for grabs, I don't see any reason why one would ever want to change this implementation.
Or does he do this just as an indicator that this class is intended as a potential base class?