J
John Carson
Jacek Dziedzic said:Hello!
I have a templated class that serves as a simple vector of
elements.
template <typename T>
class simple_vector : public math_object {
// ... lots of simple_vector operations
// the trouble begins here:
T sum() {
// calculates and returns a sum of all elements of the vector
}
};
The trouble begins whenever I try to have a vector that would
hold elements of, say, double[6]. Trying to instantiate that
gives an error, because the return type of sum() becomes an
array, which is impossible.
Is there a simple way to let the user have instances of
simple_vector<int> for which the sum() operation makes sense
while also allowing simple_vector<double[6]> to be instantiated
and only break upon trying to sum() these?
I was hoping that specialization would fix this, but whenever
I try to move the sum() function out of the template declaration
and make it a
template<> simple_vector<int>::sum() {
}
the compiler complains that the template does not contain a
function called sum(). But of course leaving a declaration of
sum as T sum() within the template declaration will lead to
the same error that sum() can't return an array.
I've googled c.l.c++ only to begin to suspect that I need function
specialization and not template specialization and that it cannot
be done. Is it so?
You can return a pointer or reference to an array if a pointer or reference
would be acceptable for all types. Alternatively, you could make sum() a
friend of the class rather than a member.
Finally, you could specialise the entire class rather than attempting to
specialise just a member function. In that case you must declare and define
the entire class again for the particular type you are interested in. To do
this, you first declare the general class. Then you declare the specialised
version, which may but need not have anything in common with the general
case, e.g.,
#include <iostream>
template <typename T>
class simple_vector
{
T t1, t2;
public:
void print() { std::cout << t1 << '\n'; }
T sum()
{
return t1+t2;
}
};
template <>
class simple_vector<double[6]>
{
double d[6];
public:
simple_vector()
{
for (int i=0; i<6; ++i)
d = i*i;
}
void print()
{
for (int i=0; i<6; ++i)
std::cout << d<< '\n';
}
};
int main()
{
simple_vector<double[6]> v;
v.print();
return 0;
}