开发者

"No matching function call" in template function

I keep getting the following error when trying to write a template function:

main.cpp|17|error: no matching function for call to ‘dotproduct(vector<float, 3u>&, vector<float, 3u>&)’|

I've searched on the error and found some other cases where a non-type template parameter could prove problematic if the parameter was a float or a double. Im using a non-type template parameter of size_t to determine the size of matrices and vectors.

I have the following classes:

matrix:

template<class element_t, size_t rows, size_t columns>
class matrix
{
private:
  element_t elements_[rows*columns];
  // ...
};

vector:

template<class element_t, size_t size>
class vector
  : public matrix<element_t, size, 1>
{
  //...
};

my function:

template<class vector_t>
typename vector_t::element_t dotproduct开发者_如何转开发(const vector_t &vector0, const vector_t &vector1)
{
  typename vector_t::element_t result_(0);
  for(size_t index_ = 0; index_ < vector_t::rows * vector_t::colums; ++index_){
    result_ += vector0[index_] * vector1[index_];
  }

  return result_;
}

called from:

int main(int count, char *arguments[])
{
  typedef vector<float, 3> vec3;

  vec3 a = {1.0f, 2.0f, 3.0f}, b = {3.0f, 2.0f, 1.0f};

  std::cout << dotproduct(a, b) << std::endl;
  std::cin.get();
}

gcc version 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4)


Names of template parameters may only be used inside the class (or function) template to which the template parameter list corresponds. It makes sense - standard makes no guarantees about template parameter names; they might be different even between two declarations!

Consider:

template <typename U, typename T>
class A;

template <typename T, typename U>
class A
{ };

int main()
{
  A<int, char>::T some_variable; // which type parameter to use?
}

Because names of template parameters cannot be used, your function template is removed from overload candidates and because there are no other functions, overload resolution fails (basically what bluescarni said).

Correct way to handle this is to typedef the template name. Once you do, the name becomes usable even from outside of class/function (well, unless it's private).

To correct your example, you need:

template<class Element, size_t rows, size_t columns>
class matrix
{
public:
  typedef Element element_t;
private:
  element_t elements_[rows*columns];
  // ...
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜