模板功能中的“无匹配函数调用”

时间:2011-06-05 21:15:47

标签: templates c++11 function-templates

尝试编写模板函数时,我一直收到以下错误:

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

我搜索了错误并发现了一些其他情况,如果参数是float或double,非类型模板参数可能会出现问题。我使用size_t的非类型模板参数来确定矩阵和向量的大小。

我有以下课程:

矩阵

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

矢量:

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

我的职能:

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_;
}

来自:

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版本4.5.2(Ubuntu / Linaro 4.5.2-8ubuntu4)

1 个答案:

答案 0 :(得分:2)

模板参数的名称只能在模板参数列表所对应的类(或函数)模板中使用。这是有道理的 - 标准不保证模板参数名称;即使在两个声明之间,它们可能会有所不同!

考虑:

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?
}

因为模板参数的名称不能使用,所以你的函数模板会从重载候选项中删除,因为没有其他函数,重载决策失败(基本上是bluescarni所说的)。

处理此问题的正确方法是typedef模板名称。一旦这样做,即使从类/函数之外,该名称也可以使用(除非它是private)。

要更正您的示例,您需要:

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