简体   繁体   English

C ++无法专门化函数模板

[英]C++ Failed to specialize function template

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]'. 我遇到的错误是:'无法专门化函数模板'T sumfun(T&,size_t)与以下模板参数: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. 我试过'模板coord sumfun(T&ob,size_t ndim)',但它会产生更多错误。

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: 我无法更改main函数,因此参数必须如下:

coord sum = sumfun(tab, sizeof(tab)/sizeof(coord)); coord sum = sumfun(tab,sizeof(tab)/ sizeof(coord));

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()是一个函数声明,这就是我将其更改为T sum = T() T sum{}; would also work. 也会有用。

Edit : If you can't change main , then add a second parameter for ndim . 编辑 :如果您无法更改main ,则为ndim添加第二个参数。 You can then check whether this number is not larger than N : 然后,您可以检查此数字是否不大于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: 当然,你也可以使用std::accumulate ,作为一个非常懒惰的程序员,它将是我的首选解决方案:

coord sum = std::accumulate(std::begin(tab), std::end(tab), coord());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM