Reputation: 107
i have a problem with function template. The error i have is: ' Failed to specialize function template 'T sumfun(T &,size_t) with the following template arguments: coord [3]'. Does anyone know how to correct that? I tried 'template coord sumfun(T &ob, size_t ndim)', but it makes even more errors.
template <class T> T sumfun(T &ob, size_t ndim){
T sum();
for(size_t i = 0 ; i <= ndim ; i++)
sum + = ob[i];
return sum;
};
class coord
{
double *crd;
public:
coord(){crd[0]=0;crd[1]=0;};
coord(double xx, double yy) {
alloc();
crd[0] = xx; crd[1] = yy;
}
coord & operator + ( const coord &prawy);
private:
void alloc() {
try {
crd = new double [2];
}catch(bad_alloc) {
}
}
};
coord & coord::operator+(const coord &prawy){
coord tmp(0,0);
tmp.crd[0] = crd[0] + prawy.crd[0];
tmp.crd[1] = crd[1] + prawy.crd[1];
return tmp;
};
int _tmain(int argc, _TCHAR* argv[])
{
coord tab[] = {
coord(0, 0), coord(1,2), coord(2, 1) };
coord sum = sumfun(tab, sizeof(tab)/sizeof(coord));
//cout << sum;
system("pause");
return 0;
}
I cant change main function, so arguments must be like:
coord sum = sumfun(tab, sizeof(tab)/sizeof(coord));
Upvotes: 0
Views: 228
Reputation: 227410
The problem is that you are passing an array, but the syntax for passing an array requires its size. Fortunately, you can let template deduction figure out the size for you:
template <class T, std::size_t N>
T sumfun(const T (&ob)[N])
{
T sum = T();
for(std::size_t i = 0 ; i < N ; ++i)
sum += ob[i];
return sum;
}
Also note that T sum()
is a function declaration, which is why I have changed that to T sum = T()
. T sum{};
would also work.
Edit: If you can't change main
, then add a second parameter for ndim
. You can then check whether this number is not larger than N
:
template <class T, std::size_t N>
T sumfun(const T (&ob)[N], std::size_t ndim)
{
if (ndim > N)
// error, raise an exception or something
T sum = T();
for(std::size_t i = 0 ; i < ndim; ++i)
sum += ob[i];
return sum;
}
Of course, you can also use std::accumulate
, which, as an extremely lazy programmer, would be my preferred solution:
coord sum = std::accumulate(std::begin(tab), std::end(tab), coord());
Upvotes: 2